Angular Framework
Angular Framework
Angular framework is based on four core concepts and they are as follows −
Components.
Templates with Data binding and Directives.
Modules.
Services and dependency injection.
// src/app/app.component.ts
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Expense Manager';
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ExpenseManager</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
Angular8 2
String interpolation
Event binding
Angular8 4
Events are actions like mouse click, double click, hover or any keyboard and mouse
actions. If a user interacts with an application and performs some actions, then
event will be raised. It is denoted by either parenthesis () or on-. We have different
ways to bind an event to DOM element. Let’s understand one by one in brief.
Property binding
Property binding is used to bind the data from property of a component to DOM
elements. It is denoted by [].
Let’s understand with a simple example.
Add the below code in test.component.ts file.
export class TestComponent {
userName:string = "Peter";
}
Add the below changes in view test.component.html,
<input type="text" [value]="userName">
Attribute binding
Attribute binding is used to bind the data from component to HTML attributes. The
syntax is as follows −
<HTMLTag [attr.ATTR]="Component data">
For example,
<td [attr.colspan]="columnSpan"> ... </td>
Let’s understand with a simple example.
Angular8 5
Class binding
Class binding is used to bind the data from component to HTML class property.
The syntax is as follows −
<HTMLTag [class]="component variable holding class name">
Class Binding provides additional functionality. If the component data is boolean,
then the class will bind only when it is true. Multiple class can be provided by string
(“foo bar”) as well as Array of string. Many more options are available.
For example,
<p [class]="myClasses">
Let’s understand with a simple example.
Add the below code in test.component.ts file,
export class TestComponent {
myCSSClass = "red";
applyCSSClass = false;
}
Add the below changes in view test.component.html.
<p [class]="myCSSClass">This paragraph class comes from *myClass*
property </p>
<p [class.blue]="applyCSSClass">This paragraph class does not
apply</p>
Add the below content in test.component.css.
.red {
color: red;
}
.blue {
color: blue;
}
Style binding
Style binding is used to bind the data from component into HTML style property.
The syntax is as follows −
<HTMLTag [style.STYLE]="component data">
Angular8 6
For example,
<p [style.color]="myParaColor"> ... </p>
Let’s understand with a simple example.
Add the below code in test.component.ts file.
myColor = 'brown';
Add the below changes in view test.component.html.
<p [style.color]="myColor">Text color is styled using style
binding</p>
NgModel
Attribute directives
Used to add new attributes for the existing HTML elements to change
its look and behaviour.
<HTMLTag [attrDirective]='value' />
For example,
<p [showToolTip]='Tips' />
Structural directives
Structural directives
NgIf
<p>test works!</p>
<div *ngIf="true">Display data</div>
Angular8 8
ngIfElse directive
<p>ngIfElse example!</p>
<div *ngIf="isLogIn; else isLogOut">
Hello you are logged in
</div>
<ng-template #isLogOut>
You're logged out..
</ng-template>
ngFor directive
<h2>ngFor directive</h2>
<ul>
<li *ngFor="let l of list">
{{l}}
</li>
</ul>
trackBy
t is used to track when elements are added or removed. It is performed by trackBy method. It has two
arguments index and element. Index is used to identity each element uniquely. Simple example is
defined below.
export class TestComponent {
studentArr: any[] = [ {
"id": 1,
"name": "student1"
},
{
"id": 2,
"name": "student2"
},
{
"id": 3, "name": "student3"
},
{
"id": 4,
"name": "student4"
}
];
trackByData(index:number, studentArr:any): number {
return studentArr.id;
}
NgSWitch
Angular8 9
<h2>ngSwitch directive</h2>
<ul [ngSwitch]="logInName">
<li *ngSwitchCase="'user'">
<p>User is logged in..</p>
</li>
<li *ngSwitchCase="'admin'">
<p>admin is logged in</p>
</li>
<li *ngSwitchDefault>
<p>Please choose login name</p>
</li>
</ul>
Attribute directives
ngStyle
<p [ngStyle]="{'color': 'blue', 'font-size': '14px'}">
paragraph style is applied using ngStyle
</p>
ngClass
Custom directives
user defined directives and it is called Custom directives.
ng-template
NgForOf directive
Component directives
Component directives are based on component. Actually, each component can be
used as directive. Component provides @Input and @Output decorator to send and
receive information between parent and child components.
Pipes
are referred as filters. It helps to transform data and manage data within
interpolation, denoted by {{ | }}. It accepts data, arrays, integers and strings as
inputs which are separated by ‘|’ symbol.
Adding parameters
Create a date method in your test.component.ts file.
export class TestComponent {
presentDate = new Date();
}
Now, add the below code in your test.component.html file.
<div>
Today's date :- {{presentDate}}
</div>
Now, run the application, it will show the following output −
Today's date :- Mon Jun 15 2020 10:25:05 GMT+0530 (IST)
Here,
Angular8 12
Chained pipes
We can combine multiple pipes together.
<div>
Date with uppercase :- {{presentDate | date:'fullDate' |
uppercase}} <br/>
Date with lowercase :- {{presentDate | date:'medium' |
lowercase}} <br/>
</div>
Built-in Pipes
Angular 8 supports the following built-in pipes. We will discuss one by one in brief.
AsyncPipe
The Async pipe performs subscription for time changing in every one seconds and
returns the result whenever gets passed to it. Main advantage is that, we don’t need
to call subscribe on our timeChange and don’t worry about unsubscribe, if the
component is removed.
Add the below code inside your test.component.html.
Angular8 13
<div>
Seconds changing in Time: {{ timeChange | async }}
</div>
CurrencyPipe
It is used to convert the given number into various countries currency format.
Consider the below code in test.component.ts file.
import { Component, OnInit } from '@angular/core'; @Component({
selector: 'app-test',
template: `
<div style="text-align:center">
<h3> Currency Pipe</h3>
<p>{{ price | currency:'EUR':true}}</p>
<p>{{ price | currency:'INR' }}</p>
</div>
`,
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
price : number = 20000; ngOnInit() {
}
}
€20,000.00
₹20,000.00
SlicePipe
Slice pipe is used to return a slice of an array. It takes index as an argument. If you
assign only start index, means it will print till the end of values. If you want to print
specific range of values, then we can assign start and end index.
We can also use negative index to access elements. Simple example is shown
below −
test.component.ts
import { Component, OnInit } from '@angular/core'; @Component({
selector: 'app-test',
template: `
<div>
<h3>Start index:- {{Fruits | slice:2}}</h3>
<h4>Start and end index:- {{Fruits | slice:1:4}}</h4>
Angular8 14
}
}
DecimalPipe
}
}
PercentPipe
JsonPipe
It is used to transform a JavaScript object into a JSON string. Add the below code
in test.component.ts file as follows −
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `
<div style="text-align:center">
<p ngNonBindable>{{ jsonData }}</p> (1)
<p>{{ jsonData }}</p>
<p ngNonBindable>{{ jsonData | json }}</p>
<p>{{ jsonData | json }}</p>
</div>
`,
styleUrls: ['./test.component.scss']
})
export class TestComponent {
jsonData = { id: 'one', name: { username: 'user1' }}
}
Now, run the application, you could see the below output on your screen −
{{ jsonData }}
(1)
[object Object]
{{ jsonData | json }}
{ "id": "one", "name": { "username": "user1" } }
Angular8 16
Reactive programming
enables the data stream to be emitted from one source called Observable and the
emitted data stream to be caught by other sources called Observer through a
process called subscription. This Observable / Observer pattern or
simple Observer pattern greatly simplifies complex change detection and
necessary updating in the context of the programming.
JavaScript does not have the built-in support for Reactive Programming. RxJs is a
JavaScript Library which enables reactive programming in JavaScript. Angular
uses RxJs library extensively to do below mentioned advanced concepts −
Observable
Subscribing process
Subscribing to an Observable is quite easy. Every Observable object will have a
method, subscribe for the subscription process. Observer need to implement three
callback function to subscribe to the Observable object. They are as follows −
next − Receive and process the value emitted from the Observable
error − Error handling callback
complete − Callback function called when all data from Observable are
emitted.
Once the three callback functions are defined, Observable’s subscribe method has
to be called as specified below −
const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);
// observer
const observer = {
next: (num: number) => { this.numbers.push(num);
this.val1 += num },
error: (err: any) => console.log(err),
complete: () => console.log("Observation completed")
};
numbers$.subscribe(observer);
Here,
next − method get the emitted number and then push it into the local
variable, this.numbers.
next − method also adding the number to local variable, this.val1.
error − method just writes the error message to console.
complete − method also writes the completion message to console.
We can skip error and complete method and write only the next method as shown
below −
number$.subscribe((num: number) => { this.numbers.push(num);
this.val1 += num; });
Operations
filter − Enable to filter the data stream using callback function.
const filterFn = filter( (num : number) => num > 5 );
const filteredNumbers$ = filterFn(numbers$);
filteredNumbers$.subscribe( (num : number) => {
this.filteredNumbers.push(num); this.val2 += num } );
Angular8 18
map − Enables to map the data stream using callback function and to change the
data stream itself.
const mapFn = map( (num : number) => num + num ); const
mappedNumbers$ = mappedFn(numbers$);
pipe − Enable two or more operators to be combined.
const filterFn = filter( (num : number) => num > 5 );
const mapFn = map( (num : number) => num + num ); const
processedNumbers$ = numbers$.pipe(filterFn, mapFn);
processedNumbers$.subscribe( (num : number) =>
{ this.processedNumbers.push(num); this.v
})
export class AppModule {}