Angular
Angular
Angular is a platform and framework for building single-page client applications using HTML and
TypeScript. Angular is written in TypeScript and is developed by a team at Google and a community
of individuals and corporations. Angular combines declarative templates, dependency injection, end-
to-end tooling, and integrated best practices to solve development challenges. Angular empowers
developers to build applications that live on the web, mobile, or desktop.
Angular is often called a “Platform” because it provides a comprehensive solution to building client-
side applications by combining declarative templates, dependency injection, end-to-end tooling, and
integrated best practices to solve development challenges.
Components: These are the basic building blocks of an Angular application. A component
controls a patch of the screen called a view.
Modules: Angular apps are modular, and Angular has its own modularity system called
NgModules. Every Angular app has at least one root module, conventionally named
AppModule.
Templates: Templates are HTML with Angular-specific elements and attributes. Angular
combines the template with information from the component and the application to render
the dynamic view that users see.
Data Binding: This is the automatic synchronization of data between the model and view
components. Angular supports two-way data binding, meaning that changes in the
application state affect the UI and vice versa.
Directives: Directives are classes that add additional behavior to elements in your Angular
applications. With Angular’s built-in directives, you can manage forms, lists, styles, and what
users see.
Services and Dependency Injection: For data or logic that isn’t associated with a specific
view and that you want to share across components, you create a service class. Angular’s
dependency injection system provides services to your components.
Routing: The Angular Router enables navigation from one view to the next as users perform
application tasks.
Full-Fledged Framework: Angular is not just a library; it’s a full-fledged framework that
provides everything you need to build a client-side application. This includes a wide range of
features out of the box, such as routing, form validation, state management, and more,
which can simplify the development process and reduce the need for additional libraries.
TypeScript: Angular is built using TypeScript, which offers static typing. This can lead to
better tooling, more predictable code, and the ability to catch errors early. TypeScript has
been appreciated for its ability to catch errors and bugs at the development stage, using
types, interfaces, and decorators, which can help to maintain larger codebases more
efficiently.
Two-Way Data Binding: Angular’s two-way data binding feature allows for the automatic
synchronization of data between the model and view components within the application.
This means that when the data in the model changes, the view reflects these changes
immediately and vice versa, which reduces the need for DOM manipulation and can
significantly simplify the development process.
Declarative UI: Angular uses HTML to define the UI of the application. HTML is a declarative
language, which is more intuitive and less complex than defining the interface procedurally
in JavaScript.
Dependency Injection: Angular’s dependency injection system allows for greater flexibility in
how components and services are connected and provides a way to swap out dependencies
easily. This is particularly useful for testing and application maintenance.
Directives: Angular has a set of built-in directives that can add behavior to DOM elements
and manipulate DOM attributes in interesting ways. Custom directives can also be created
for reusable features.
Rich Ecosystem: Angular provides a rich ecosystem with additional tools and components.
Numerous libraries integrate with Angular, such as Angular Material for UI components and
NGX-Bootstrap for Bootstrap components in Angular projects.
RxJS Libraries: Angular uses RxJS, a library for reactive programming using observables, to
handle asynchronous data calls. RxJS provides powerful composition techniques and error-
handling mechanisms, making it easier to compose asynchronous or callback-based code,
which can significantly simplify the handling of event-driven applications like SPAs.
Cross-Platform Development: Angular supports cross-platform development. You can use
Angular for web, mobile native, and mobile desktop applications. With technologies like Ionic
for mobile apps or Electron for desktop apps, Angular extends its reach beyond browser-
based applications.
src Folder:
This is the source folder of our angular application. That means this is the place where we need to
put all our application source code. So, every component, service class, modules, everything we need
to put in this folder only. Whenever we create an angular project, by default the angular framework
creates lots of files folder within the src folder.
app Folder:
This is the application folder. Whenever you want to create any component, service, or module, you
need to create it within this app folder.
assets Folder:
This is the folder where you can store the static assets like images, icons, etc. which needed to be
copied extensively while building your application.
environments Folder:
This folder is basically used to set up different environments. Here, you can find two files as shown in
the below image.
You can use this file to store environment (either production or development environment) specific
configuration such as the database credentials or server IP addresses. These two files are as follows:
1. environment.prod.ts. This file for the production environment
index.html:
This HTML file contains HTML code with the head and body section. It is the starting point of your
application or you can say that this is where our angular app bootstraps. If you open it you will find
that there are no references to any stylesheet (CSS) nor JS files this is because all dependencies are
injected during the build process.
main.ts file:
This is the entry point for our angular application. If you ever worked with programming languages
like Java or C or C#, then you can compare this with the main() method of such application.
In TypeScript, we can do this by using the “import” and “export” keywords. That means the modules
which need to be exposed should be declared using the “export” keyword while the modules which
want to import the exported modules should have the import keyword.
For any angular application, there should be at least one module. The AppModule (app.module.ts
file) is the default module or root module of our angular application.
Once you open the app.module.ts file, then you will find the following code in it.
Here, AppModule is the module name and it is decorated with the @NgModule decorator.
The @NgModule imported from the angular core library i.e. @angular/core. Here, we
call NgModule a decorator because it is prefixed with @ symbol. So, whenever you find something in
angular, that is prefixed with @ symbol, then you need to consider it as a decorator.
Declarations Array (declarations):
The declarations array is an array of components, directives, and pipes. Whenever you add a new
component, first the component needs to be imported and then a reference of that component must
be included in the declarations array. By default AppComponent (app.component.ts file) is created
when you create a new angular project and you can find this file within the app folder which you can
find inside the src folder.
the component name is AppComponent. And in the root module, first, this component
(AppComponent) is imported and then its reference is included in the declarations array.
If you declare a component in one module, then you can’t declare the same component in another
module. If you try then you will get an error when you run your application. At the moment you
already declared the EmployeeLoginComponent within the Employee module and if you try to
declare it again on the AppModule module then you will get an error when you run your application.
The decorator provides metadata to angular classes, property, value, method, etc. and decorators
are going to be invoked at runtime.
Understanding Decorators:
If you open the app.module.ts file, then you will find AppModule which is the root module of the
angular application. Further, if you notice, this AppModule is nothing but it’s a class. Now the
question is why we call this class a Module? This is because this class is decorated
with @NgModule decorator as shown in the below image. Here, the @NgModule decorator
provides the necessary metadata to make the AppModule class as a module.
Note: If you want to create a module in angular, then you must decorate your class with @NgModule
decorator. Once a class is decorated with @NgModule decorator, then only the class works as a
module.
2. Property Decorators: @Input and @Output (These two decorators are used inside a class)
3. Method Decorators: @HostListener (This decorator is used for methods inside a class like a
click, mouse hover, etc.)
Every Angular application has at least one component that is used to display the data on the
view. Technically, a component is nothing but a simple typescript class and composed of
three things as follows:
Template:
The template is used to define an interface with which the user can interact. As part of that
template, you can define HTML Mark-up; you can also define the directives, and bindings,
etc. So in simple words, we can say that the template renders the view of the application
with which the end-user can interact i.e. user interface.
Class:
The Class is the most important part of a component in which we can write the code which is
required for a template to render in the browser The angular component class can also
contain methods, variables, and properties like other programming languages. The angular
class properties and variables contain the data which will be used by a template to render on
the view. Similarly, the method in an angular class is used to implement the business logic
like the method does in other programming languages.
Decorator:
In order to make an angular class as a component, we need to decorate the class with
the @Component decorator. The point that you need to remember is decorators are
basically used to add metadata.
We need to decorate the class with @Component decorator which adds metadata to the class. We
need to use @ symbol to apply a decorator to a class. Once you apply the @Component decorator to
your class then only your class becomes a component.
The @Component decorator in angular provides metadata to a component that determines how to
process, instantiate and use the component at runtime. If you are a dot net developer then you can
compare this with the attribute in C#.
1. changeDetection – change the detection strategy used by this component.
2. templateUrl – URL in an external file that contains a template for the view.
4. viewProviders – list of providers available for this component and the view of their children.
8. styleUrls – URL list for style sheets that will be applied to the view of this component.
10. styles – styles defined online that will be applied to the view of this component.
11. preserveWhitespaces – Using this property, we can remove all whitespaces from the
template.
External Template
Inline Templates:
In Angular applications, the inline templates are directly specified in the component
decorator using the template property. That means you need to write the required HTML
inside the typescript file.
Yes, you can include the above HTML code within a pair of either single
quotes or double quotes as long as your HTML code is in a single line , but if
you are HTML code is in the multiple lines then use the backticks(``).
External Template:
The External templates define the HTML in a separate file and refer to that file using templateUrl
property of Component decorator.
According to Angular, when you have a complex view (i.e. a view with more than 3 lines) then go
with templateUrl (use external file) else use the template (inline HTML) properly of the component
decorator.
When you use an inline template, then you will lose the intelligence support, code-completion, and
formatting features of Visual Studio. But with an external template, you will get the intelligence
support, code-completion, and formatting features of Visual Studio
How to nest a component inside another component in angular?
In order to nest a component inside another component, you need to follow the below two steps.
Step1:
Open the “app.module.ts” file which is present inside the app folder, and then do the following
things.
First, you need to import the StudentComponent and then you need to add the StudentComponent
to the declarations array as shown in the below image.
Step2:
Open your parent component i.e. “app.component.ts” file and then include “app-student” as a
directive as shown in the below image. If you remember, the “app-student” that we used here is
nothing but a selector of StudentComponent i.e. our child component.
At this point, launch the browser developer’s tools and click on the “Elements” tab and notice <app-
app> and <app-stduent> directives are rendered as HTML tag as shown in the below image. Here,
you can see the app-student render inside the app-root tag.
Styling Angular Components
Option1: Styling Angular Components using External Stylesheets
Option2: Styling Angular Components using Inline Styles
Option3: Styling in the component HTML file
Option4: Styling in the Component file
Option5: Styling using the @component decorator styleUrls property
The angular framework provides one concept called Data Binding which is used for synchronizing the
data and the user interface (called a view).
1. One-way Data Binding- where a change in the state affects the view (i.e. From Component
to View Template) or change in the view affects the state (From View Template to
Component).
2. Two-way Data Binding- where a change from the view can also change the model and
similarly change in the model can also change in the view (From Component to View
Template and also From View template to Component).
In order to understand this better and remember, please have a look at the following image which
describes the classification of Data Binding.
The Interpolation in Angular allows you to place the component property name in the view template,
enclosed in double curly braces i.e. {{propertyName}}. So, the Angular Interpolation is a technique
that allows the user to bind a value to a UI element.
Method Interpolation in Angular Application:
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
In Property Binding, there is a source and target. For example, consider the below span tag.
span[innerHTML] = ‘FirstName’.
Here, innerHTML is the target that is a property of span tag and FirstName is the source that is the
component property.
But there are some scenarios where we need to use interpolation instead of property binding. For
example, if you want to concatenate strings then you need to use angular interpolation instead of
property binding as shown in the below image.
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
{{MaliciousData}}
</div>`
})
Now, when we run the application, the Angular interpolation sanitizes the malicious content and
displays the following in the browser.
@Component({
selector: 'app-root',
</div>`
})
The Property Binding handles the malicious HTML content in a slightly different manner and when
you run the application, you will get the following output in the browser. But the most important
point that you need to keep in mind is, both property binding and interpolation protect us from
malicious HTML content.
What is DOM?
The DOM stands for Document Object Model. When a browser loads a web page, then the browser
creates the Document Object Model (DOM) for that page. For example, let say we have a page with
the following HTML.
When the above HTML is loaded by the browser, then it creates the Document Object Model (DOM)
as shown in the below image.
So in simple words, we can say that the DOM is an application programming interface (API) for the
HTML, and we can use the programming languages like JavaScript or JavaScript frameworks like
Angular to access and manipulate the HTML using their corresponding DOM objects.
In other words, we can say that the DOM contains the HTML elements as objects, their properties,
methods, and events and it is a standard for accessing, modifying, adding or deleting HTML
elements.
What is the difference between the HTML element attribute and DOM property?
1. The Attributes are defined by HTML whereas the properties are defined by the DOM.
2. The attribute’s main role is to initializes the DOM properties. So, once the DOM initialization
complete, the attributes job is done.
3. Property values can change, whereas the attribute values can never be changed.
Now, you may be intended to use the ColumnSpan property to set the colspan attribute of the th
element using angular interpolation as shown in the below image.
You will also get the same error if you try to bind the colspan property using the Property Binding
Technique. Let us prove this. First, modify the colspan binding in the app.component.html file as
shown below.
With the above Property Binding in place, now if you compile the project, then you will get the same
error as shown in the below image.
We get the above error. The reason for this error is, we do not have a corresponding property in the
DOM for the colspan attribute. In order to solve the above error, what you need to do is you need to
use Angular Attribute Binding, which will set the colspan attribute value.
Now run the application and you should get the output as expected.
Note: The Angular team recommends using the property binding or Interpolation whenever possible
and use the attribute binding only when there is no corresponding element property to bind
.boldClass{
font-weight:bold;
.italicClass{
font-style:italic;
.colorClass{
color:red;
}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
AddCSSClasses() {
let Cssclasses = {
boldClass: this.ApplyBoldClass,
italicsClass: this.ApplyItalicsClass
};
return Cssclasses;
2. The ngClass directive is bind to the AddCSSClasses() method of the AppComponent class
3. Here, AddCSSClasses() is method that returns an object with 2 key/value pairs. The key is
the CSS class name and the value can be true or false. If the value is true then it will add
the class and when the value is False then it will remove the class.
4. Since both the keys (boldClass & italicsClass) are set to true, both classes will be added to
the button element
5. The let is a new type of variable declaration in JavaScript. let is similar to var in some
respects. In our upcoming article, we will discuss let and var in detail as well as discuss the
differences between them. For this example, you can also use var and it should work.
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</button>
</div>`
})
}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div>
</button>
</div>`
})
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
AddCSSStyles() {
let CssStyles = {
'font-weight': this.IsBold ? 'bold' : 'normal',
'font-size.px': this.FontSize
};
return CssStyles;
3. The AddCSSStyles() method returns an object with 3 key/value pairs. The key is a style name,
and the value is a value for the respective style property or an expression that returns the
style value.
4. The let is a new type of variable declaration in JavaScript. Instead of let you can also use var
here.
Another Example:
When the page loads for the first time, we want to display only the First Name and Last Name of
the student. We also display the “Show Details” button as shown in the below image.
When the user clicks on the “Show Details” button, we want to display the “Gender“, “Age“,
“Mobile”, and “Branch” as well. The text on the button should be changed to “Hide Details” as
shown in the below image and when the user clicks on the “Hide Details” button, then the
“Gender“, “Age“, “Mobile”, and “Branch” should be hidden and the button text should be changed
to “Show Details”.
We can achieve this very easily in angular with the help of event binding. Here we will make use of
one of the angular directives i.e. “ngIf“.
Notice we have introduced “ShowDetails” boolean property. The default value is false, so when
the page loads for the first time, we will have “Gender”, “Age”, “Mobile”, and “Branch” hidden. We
also have a method, ToggleDetails(), which will toggle the value of ShowDetails.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls:['./app.component.css']
})
ColumnSpan: number = 2;
ToggleDetails(): void {
this.ShowDetails = !this.ShowDetails;
We used ngIf structural directive on “Gender”, “Branch”, “Mobile” and “Age” <tr> elements. The *
prefix before a directive indicates, it is a structural directive. Besides ngIf, there are other structural
directives which we will discuss in our upcoming articles.
The ngIf directive conditionally adds or removes content from the DOM based on whether or not
an expression is true or false. If “ShowDetails” is true, “Gender”, “Branch”, “Mobile” and “Age”
<tr> elements are added to the DOM, else removed.
<table>
<thead>
<tr>
<th attr.colspan="{{ColumnSpan}}">
Student Details
</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td>{{FirstName}}</td>
</tr>
<tr>
<td>Last Name</td>
<td>{{LastName}}</td>
</tr>
<tr *ngIf='ShowDetails'>
<td>Branch</td>
<td>{{Branch}}</td>
</tr>
<tr *ngIf='ShowDetails'>
<td>Mobile</td>
<td>{{Mobile}}</td>
</tr>
<tr *ngIf='ShowDetails'>
<td>Gender</td>
<td>{{Gender}}</td>
</tr>
<tr *ngIf='ShowDetails'>
<td>Age</td>
<td>{{Age}}</td>
</tr>
</tbody>
</table>
<br/>
<button (click)='ToggleDetails()'>
{{ShowDetails ? 'Hide' : 'Show'}} Details
</button>
Modify app.component.css file:
Modify the app.component.css file as shown below.
table {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size:large;
border-collapse: collapse;
}
td {
border: 1px solid black;
}
thead{
border: 1px solid black;
}
Now run the application and you will see everything is working as expected as per our
requirement.
Syntax:
With event binding, you can also use the on- prefix alternative as shown in the image below. This is
known as the canonical form. It’s up to you which approach you follow. Behind the scene, they are
going to perform the same task.