0% found this document useful (0 votes)
3 views42 pages

Angular

Angular is a platform and framework for building single-page applications using HTML and TypeScript, developed by Google. It features components, modules, templates, data binding, directives, and dependency injection, providing a comprehensive solution for client-side development. Angular supports cross-platform development and is particularly suited for enterprise-level applications due to its modular architecture and rich ecosystem.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views42 pages

Angular

Angular is a platform and framework for building single-page applications using HTML and TypeScript, developed by Google. It features components, modules, templates, data binding, directives, and dependency injection, providing a comprehensive solution for client-side development. Angular supports cross-platform development and is particularly suited for enterprise-level applications due to its modular architecture and rich ecosystem.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

What is 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.

Key Features and Concepts of Angular include:

 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.

 Tooling: Angular provides a powerful command-line interface (CLI) to automate your


development workflow, including starting new projects, adding different features to your
existing projects, and running various development tasks such as testing.

 TypeScript: Angular is built with TypeScript, a superset of JavaScript with design-time


support for type safety and tooling.
Why do we need Angular?
 “Angular is an open-source JavaScript framework that simplifies code binding between
JavaScript objects and HTML UI elements.”

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.

 Component-Based Architecture: Angular’s architecture is based on components. Each


component represents a piece of the UI, and when combined, they form the entire user
interface. This modularity enables a reusable, maintainable, and testable codebase.

 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.

 MVVM (Model-View-ViewModel): Angular’s design pattern encourages developers to


separate the application logic from the user interface layer, which can improve the
maintainability and testability of the application.

 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.

 Use Case Fit: Angular might be particularly well-suited to enterprise-level applications or


projects where the full framework capabilities can be utilized. Applications that require a
solid structure, long-term maintainability, and scalability may particularly benefit from what
Angular offers.

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

2. environment.ts. This file for the development 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.

What is a Module in Angular?


In Angular, a module is a container. In order words, we can say that a module is a mechanism to
group components, services, directives, pipes. So, the grouping of related components, services,
pipes, and directives is nothing but a module in angular.

Why we need Modules in Angular?


Modular development is one of the most important aspects of software development. Good
software will always have self-contained modules. So, in Angular, you would like to create separate
physical typescript or JavaScript files that will have self-contained code. Then definitely you would
have some kind of reference mechanism by using which the modules can be referred from the places
where you want to use these modules.

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.

Imports Array (imports):


In the imports section, we need to include other modules (Except @NgModule). By default, it
includes two modules i.e. BrowserModule and AppRoutingModule. Like the components, here also,
first you need to import the modules, and then you need to include a reference of that module in the
imports section
Providers Array (providers):
We need to include the services in the provider’s section. Whenever you create any service for your
application, first you need to include a reference of that service in the provider’s section and then
only you can use that service in your application.

Bootstrap Array (bootstrap):


This section is basically used to bootstrap your angular application i.e. which component will execute
first. At the moment we have only one component i.e. AppComponent and this is the component
that is going to be executed when our application run. So, this AppComponent is included in the
bootstrap array

How to create a Module in Angular?


In order to create a module in angular using Angular CLI, you need to use the command as shown in
the below image. Here g means generate and you use either g or generate to create the module.

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.

Adding Employee module reference in AppModule import section


In order to use the EmployeeLoginComponent, you need to include the reference of the Employee
module into the import section of your root module i.e. the AppModule as shown in the below
image.
What are Angular Decorators?
Decorators are the features of Typescript and are implemented as functions. The name of the
decorator starts with @ symbol following by brackets and arguments. That means in angular
whenever you find something which is prefixed by @ symbol, then you need to consider it as a
decorator.

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.

Commonly used Decorators:


1. @NgModule to define a module.

2. @Component to define components.

3. @Injectable to define services.

4. @Input and @Output to define properties, etc.

All the above decorators are imported from @angular/core


For example, if you want to use the component decorator, then first you need to import the
component decorator as shown below.

import { Component } from ‘@angular/core’;

Types of Decorators in Angular:


In Angular, the Decorators are classified into 4 types. They are as follows:

1. Class Decorators: @Component and @NgModule

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.)

4. Parameter Decorators: @Inject (This decorator is used inside class constructor).

Note: In Angular, each decorator has a unique role.

What are Angular components?


The core concept or the basic building block of Angular Application is nothing but the
components. That means an angular application can be viewed as a collection of
components and one component is responsible for handling one view or part of the view. An
Angular Component encapsulates the data, the HTML Mark-up, and the logic required for a
view.

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:

1. Class (Typescript class)

2. Template (HTML Template or Template URL)

3. Decorator (@Component Decorator)

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.

Note: Whenever we create any component, we need to define that component in


@NgModule.

Applying the component decorator to the class:


The next step is to decorate the class with the @Component decorator. As we already
discussed in angular, a class will only become a component when it is decorated with the
@Component decorator as shown in the below image.

Component Decorator Selector Property:


If you want to use a component on any HTML page in your angular application, then you must have
to specify the selector property of the Component decorator. This selector property of the
component decorator will become a directive i.e. in this case the directive will be <app-root> on the
HTML page. But when you run the application, this directive <app-root> in the HTML page is
replaced with the content specified by the templateUrl properties of the component decorator. If
you look at the templateUrl property value, it is holding one HTML Page
i.e. app.component.html and you can find this file in the app folder of your project. So, finally,
this app.component.html file content will be display in the browser. If you open the index.html file,
then you will find this <app-root> selector as shown in the below image.
TemplateUrl:
As we already discussed the templateUrl property of the @Component decorator actually contains
the HTML file that you want to render on an HTML page. Along with the templateUrl property you
can also use the template property.

Decorating the class with @Component decorator:

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.

What Happens when we build the angular application?


When we build the angular application, the TypeScript files i.e. the .ts files are compiled to the
respective JavaScript files i.e. the .js file. These javascript files are going to be rendered by the
browser. As we have a typescript file with the name app.component.ts, so when we build the project
then it will create a javascript file with the name app.componet.js.

Understanding Angular Component and module architecture:


As we already discussed, the main aim of Angular is to bind the model and the view. In Angular, the
binding code is technically called a Component. In enterprise projects, we can have a lot of
components. With many components, it is very difficult for us to handle the project. So, what we can
do is, we will group the components logically into modules.
1. Components: – This will contain the binding logic to bind the UI and the model.

2. Modules: – This will logically group components.

What is the Component Decorator in Angular?


Whenever you want to make a class as a component, then you need to decorate that class
with @Component decorator.

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.

3. template – template defined inline template for the view.

4. viewProviders – list of providers available for this component and the view of their children.

5. animations – animation’s list of this component.

6. moduleId – Module ID ES / CommonJS of the file in which this component is defined.

7. encapsulation – strategy of style encapsulation used by this component.

8. styleUrls – URL list for style sheets that will be applied to the view of this component.

9. interpolation – custom interpolation markers used in the template 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.

12. entryComponents – entryComponents is the list of components that are dynamically


inserted into the view of this component.
Different ways to create Templates in Angular
Inline 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.

When to use the template URL in angular applications?


When you have a complex view, then it is recommended by angular to create that complex view in
an external HTML File instead of an inline template. The angular component decorator provides a
property called templateUrl and using this property you can set the external HTML file path.

Template vs TemplateUrl in Angular:


From the application performance point of view, there are no such real differences between the
template and templateUrl property. But from the developer’s point of view, there are some
differences that we will discuss here.

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

Data binding is one of the most important features provided by Angular


Framework which allows communicating between the component and
its view.

Why do we need Data Binding?


Whenever you want to develop any data-driven web application, then as a developer you need to
keep the focus on two important things i.e. Data and the UI (User Interface) and it is more important
for you to find an efficient way to bind them (Data and UI) together. Again, the data can arrive in
several chunks and you need to update the user interface with the latest or updated data.

The angular framework provides one concept called Data Binding which is used for synchronizing the
data and the user interface (called a view).

What is Data Binding in Angular Application?


Data Binding is a process that creates a connection to communicate and synchronize between the
user interface and the data. In order words, we can say that Data Binding means to interact with the
data and view. So, the interaction between the templates (View) and the business logic is called data
binding.
Types of Data Binding in Angular:
There are two types of Data binding available. They are as follows

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.

What is Angular Interpolation?


If you want to display the read-only data on a view template (i.e. From Component to the View
Template), then you can use the one-way data binding technique i.e. the Angular interpolation.

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:

import { Component } from '@angular/core';


@Component({
selector: 'app-root',
template: `<div>
<h1> Full Name : {{ GetFullName() }} </h1>
</div>`
})
export class AppComponent {
FirstName : string = "Anurag";
LastName : string = "Mohantry";
GetFullName() : string{
return this.FirstName + ' ' + this.LastName;
}
}
Displaying Images using Angular Interpolation:

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<img src = {{ImagePath}} />

</div>`

})

export class AppComponent {

ImagePath : string = "https://dotnettutorials.net/wp-content/uploads/2019/09/cropped-


dotnettutorials.png";

What is Angular Property Binding?


The Property Binding in Angular Application is used to bind the values of component or model
properties to the HTML element. Depending on the values, it will change the existing behavior of the
HTML element. The syntax to use property is: [property] = ‘expression’

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.

How to use the Property Binding in Angular Application?


In order to understand how to use property binding in the angular application, please have a look at
the following image. As you can see in the below image, you need to specify the HTML element
property (in our example, the HTML element is span and the property is innerHTML) in a pair of the
square brackets. Then you need to specify the component class property (in our example, the
component class is AppComponent and the property is Title) in a pair of single quotes. Then at
runtime, this property value will be assigned to the HTML Property.
Achieving the same thing using Angular Interpolation and Property
Binding:
What is the difference between Property Binding and Angular
Interpolation?
Interpolation in Angular is just an alternative approach for property binding. It is a special type of
syntax that converts into a property binding.

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.

Working with non-string (Boolean) data:


When you are working with non-string values like Boolean to set the property value of an HTML
element, then you need to use property binding instead of interpolation. For example, if you want to
disable a button click event, then you need to set the disabled property of the button element using
the property binding.

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button [disabled] = 'IsDisabledClick' > Cick Here </button>

</div>`

})

export class AppComponent {

IsDisabledClick : boolean = true;

if same thing we do with the Interpolation we cant achieve because


it expects the value to be string
Providing Security to Malicious Content:
From the security point of view, both Angular data binding and Angular Interpolation protect us
from malicious HTML content before rendering it on the web browser. Let us understand this with
an example. In the following example, we are using angular interpolation to bind the malicious
<script> tag.

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

{{MaliciousData}}

</div>`

})

export class AppComponent {

MaliciousData : string = "Hello <script>alert('your application is hacked')</script>";

Now, when we run the application, the Angular interpolation sanitizes the malicious content and
displays the following in the browser.

In the below example we are using property binding.

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div [innerHTML] = 'MaliciousData'>

</div>`

})

export class AppComponent {

MaliciousData : string = "Hello <script>alert('your application is hacked')</script>";

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.

Why we need Attribute Binding in Angular Application?


In our Angular Interpolation and Property Binding articles, we discussed that they both
(Interpolation and Property Binding) are dealing with the DOM Properties but not with the HTML
attributes. But there are some HTML elements (such as colspan, area, etc) that do not have the DOM
Properties. Now the question is how to deal with such elements that do not have DOM Properties as
we can’t use Interpolation and Attribute Binding. The Answer is Angular Attribute Binding.
With Attribute Binding in Angular, you can set the value of an HTML Element Attribute directly. So,
the Attribute Binding is used to bind the attribute of an element with the properties of a component
dynamically.

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.

Once you compiled, you will get the following error.


Using Property Binding in Angular:

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.

Using Attribute Binding in Angular:


To tell the angular framework that we are setting an attribute value, we have to prefix the attribute
name with the attr and a DOT as shown below.
The same is also true when we are using angular interpolation as shown in the below image.

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

What is Angular Class Binding?


The Angular Class Binding is basically used to add or remove classes to and from the HTML elements.
It is also possible in Angular to add CSS Classes conditionally to an element, which will create the
dynamically styled elements and this is possible because of Angular Class Binding.

.boldClass{

font-weight:bold;

.italicClass{

font-style:italic;

.colorClass{

color:red;

}
import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button [class] = 'ClassesToApply' >Click Me</button>

</div>`

})

export class AppComponent {

ClassesToApply : string = 'italicClass boldClass';

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button class='colorClass' [class] = 'ClassesToApply' >Click Me</button>

</div>`

})

export class AppComponent {

ClassesToApply : string = 'italicClass boldClass';

Adding or removing a single class:

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button class='colorClass' [class.boldClass]='ApplyBoldClass'>Click Me</button>

</div>`

})

export class AppComponent {

ApplyBoldClass: boolean = true;


}

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button class='colorClass' [class.boldClass]='ApplyBoldClass'>Click Me</button>

</div>`

})

export class AppComponent {

ApplyBoldClass: boolean = false;

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button class='colorClass' [class.boldClass]='!ApplyBoldClass'>Click Me</button>

</div>`

})

export class AppComponent {

ApplyBoldClass: boolean = false;

Add or Remove multiple classes in Angular:


import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button class='colorClass' [ngClass]='AddCSSClasses()'>Click Me</button>

</div>`

})

export class AppComponent {

ApplyBoldClass: boolean = true;


ApplyItalicsClass: boolean = true;

AddCSSClasses() {

let Cssclasses = {

boldClass: this.ApplyBoldClass,

italicsClass: this.ApplyItalicsClass

};

return Cssclasses;

What we are doing here?

1. Here the colorClass is added using the class attribute

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.

What is Angular Style Binding?


The Angular Style Binging is basically used to set the style in HTML elements. You can use both
inline as well as Style Binding to set the style in the element in Angular Applications. Here, in this
article, I will show how to use both inline as well as style binding to style the HTML Elements with
examples.
import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button style='color:red'>Click Me</button>

</div>`

})

export class AppComponent {

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button style='color:red' [style.font-weight]="IsBold ? 'bold' : 'normal'">Click Me

</button>

</div>`

})

export class AppComponent {

IsBold: boolean = true;

}
import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button style='color:red' [style.font-size.px]="FontSize">Click Me

</button>

</div>`

})

export class AppComponent {

FontSize: number = 40;

Multiple Inline Styles in Angular Application:


import { Component } from '@angular/core';

@Component({

selector: 'app-root',

template: `<div>

<button style='color:red' [ngStyle]="AddCSSStyles()">Click Me </button>

</div>`

})

export class AppComponent {

IsBold: boolean = true;

FontSize: number = 40;

IsItalic: boolean = true;

AddCSSStyles() {

let CssStyles = {
'font-weight': this.IsBold ? 'bold' : 'normal',

'font-style': this.IsItalic ? 'italic' : 'normal',

'font-size.px': this.FontSize

};

return CssStyles;

What we did here?


1. Here, we add the color style using the style attribute

2. The ngStyle is bounded to AddCSSStyles() method of the AppComponent class. In


our Angular ngStyle Directive article, we will discuss this ngStyle in detail.

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.

What is Event Binding in Angular?


When a user interacts with an application in the form of a keyboard movement, button click,
mouse over, selecting from a drop-down list, typing in a textbox, etc. it generates an event. These
events need to be handled to perform some kind of action. This is where event binding comes into
the picture and in Angular Application

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“.

Modify app.component.ts file:

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']

})

export class AppComponent {

ColumnSpan: number = 2;

FirstName: string = 'Anurag';

LastName: string = 'Mohanty';

Branch: string = 'CSE';

Mobile: number = 9876543210

Gender: string = 'Male';

Age: number = 20;

ShowDetails: boolean = false;

ToggleDetails(): void {

this.ShowDetails = !this.ShowDetails;

Modify app.component.html file:


Notice the click event of the button element is bounded to ToggleDetails() method. To dynamically
change the text on the button, we are using a ternary operator:

{{ShowDetails ? ‘Hide’ : ‘Show’}} Details

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.

You might also like