Angular 8 Notes
Angular 8 Notes
It is
the default package manager for the JavaScript runtime environment
What is Angular ?
Prerequisites
Before proceeding with the various types of concepts given in this tutorial, we assume
that the readers have the basic knowledge on HTML, CSS and OOPS concepts. In
addition to this, it will be very helpful, if the readers have a sound knowledge on
TypeScript and JavaScript.
1
Single page application (SPA) is a single page (hence the name) where a
lot of information stays the same and only a few pieces need to be updated
at a time.
For example, when you browse through your email you’ll notice that not
much changes during navigation - the sidebar and header remain untouched
as you go through your inbox.
The SPA only sends what you need with each click, and your browser renders
that information. This is different to a traditional page load where the
server re-renders a full page with every click you make and sends it to
your browser.
This piece by piece, client side method makes load time must faster for
users and makes the amount of information a server has to send a lot less
and a lot more cost efficient.
You can see how to upgrade Angular CLI to version . Click Here
2
TypeScript 3.4
Angular supports TypeScript 3.4 and it is required to run your Angular
project. So you have to upgrade your TypeScript version to 3.4.
One for front end (in Angular) and one for backend (in Node.js |
Express | MongoDB). We will also create a backend API which will be used
by frontend.
o Node: 12.4.0
o Angular CLI: .0.2
o NPM: v12.4.0
o To check Node and Angular CLI version, use ng --
version command.
o To check npm version, use node -v command.
Angular Architecture
The basic building blocks of an Angular application are NgModules, which
provide a compilation context for components. NgModules collect related
code into functional sets; an Angular app is defined by a set of NgModules.
3
An app always has at least a root module that enables bootstrapping, and
typically has many more feature modules.
o Components define views, which are sets of screen elements that Angular
can choose among and modify according to your program logic and data.
o Components use services, which provide specific functionality not directly
related to views. Service providers can be injected into components as
dependencies, making your code modular, reusable, and efficient.
1. ng new angularproject
4
Install Bootstrap 4 CSS framework
Use the following command to install bootstrap in your
project.npm install bootstrap --save
1. "styles": [
2. "src/styles.css",
5
3. "./node_modules/bootstrap/dist/css/bootstrap.min.css"
4. ],
The above CSS is used that we can use the bootstrap classes inside any file.
6
Start the Angular development server using the following
command.ng serve
Angular Components
In Angular , Components and services both are simply classes with
decorators that mark their types and provide metadata which guide Angular
to do things.
Every Angular application always has at least one component known as root
component that connects a page hierarchy with page DOM. Each component
defines a class that contains application data and logic, and is associated
with an HTML template that defines a view to be displayed in a target
environment.
7
Modules
Angular NgModules are different from other JavaScript modules. Every
Angular app has a root module known as AppModule. It provides the
bootstrap mechanism that launches the application.
o Angular NgModules import the functionalities form other NgModules just like
other JavaScript modules.
o NgModules allow their own functionality to be exported and used by other
NgModules. For example, if you want to use the router service in your app,
you can import the Router NgModule.
8
program logic, and binding markup connects your application data and the
DOM.
1. Event Binding: Event binding is used to bind events to your app and
respond to user input in the target environment by updating your application
data.
Routing3
In Angular , Router is an NgModule which provides a service that facilitates
developers to define a navigation path among the different application states
and view hierarchies in their app.
o Enter a URL in the address bar and the browser will navigate to that
corresponding page.
o Click the link on a page and the browser will navigate to a new page.
o Click the browser's back or forward buttons and the browser will navigate
backward or forward according to your seen history pages.
Angular Directives
The Angular directives are used to manipulate the DOM. By using Angular
directives, you can change the appearance, behavior or a layout of a DOM
element. It also helps you to extend HTML.
9
Angular directives can be classified in 3 categories based on how
they behave:
o Component Directives
o Structural Directives
o Attribute Directives
10
Attribute Directives: Attribute directives are used to change the look and
behavior of the DOM elements. For example: ngClass directive, and ngStyle
directive etc.
ngIf Syntax
1. <p *ngIf="condition">
2. condition is true and ngIf is true.
3. </p>
4. <p *ngIf="!condition">
5. condition is false and ngIf is false.
6. </p>
The ngIf directive does not hide the DOM element. It removes the entire
element along with its subtree from the DOM. It also removes the
corresponding state freeing up the resources attached to the element.
11
The *ngIf directive is most commonly used to conditionally show an inline
template. See the following example:
1. @Component({
2. selector: 'ng-if-simple',
3. template: `
4. <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
5. show = {{show}}
6. <br>
7. <div *ngIf="show">Text to show</div>
8. `
9. })
10.export class NgIfSimple {
11. show: boolean = true;
12.}
Syntax of ngFor
See the simplified syntax for the ngFor directive:
The following Code contains a list of Top 3 movies in a movies array. Let's
build a template to display these movies in a tabular form.
13
12. {title:'Batman v Superman: Dawn of Justice',director:'Zack Snyder',cast:'Ben A
ffleck, Henry Cavill, Amy Adams',releaseDate:'March 25, 2016'},
13. {title:'Captain America: Civil War',director:'Anthony Russo, Joe Russo',cast:'Sca
rlett Johansson, Elizabeth Olsen, Chris Evans',releaseDate:'May 6, 2016'},
14. {title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer Lawrence, Olivi
a Munn, Oscar Isaac',releaseDate:'May 27, 2016'},
15. ]
16.}
17.class Movie {
18. title : string;
19. director : string;
20. cast : string;
21. releaseDate : string;
22.}
Now, open the app. component.html and add the following code:
14
19. <td>{{movie.director}}</td>
20. <td>{{movie.cast}}</td>
21. <td>{{movie.releaseDate}}</td>
22. </tr>
23. </tbody>
24. </table>
25. </div>
26. </div>
27.</div>
When you run the application, It will show the movies in tabular form.
Syntax of ngSwitch
1. <container_element [ngSwitch]="switch_expression">
2. <inner_element *ngSwitchCase="match_expresson_1">...</inner_element>
3. <inner_element *ngSwitchCase="match_expresson_2">...</inner_element>
4. <inner_element *ngSwitchCase="match_expresson_3">...</inner_element>
5. <inner_element *ngSwitchDefault>...</element>
6. </container_element>
ngSwitchCase
In Angular ngSwitchCase directive, the inner elements are placed inside the
container element. The ngSwitchCase directive is applied to the inner
elements with a match expression. Whenever the value of the match
expression matches the value of the switch expression, the corresponding
inner element is added to the DOM. All other inner elements are removed
from the DOM
15
If there is more than one match, then all the matching elements are added
to the DOM.
ngSwitchDefault
You can also apply the ngSwitchDefault directive in Angular . The element
with ngSwitchDefault is displayed only if no match is found. The inner
element with ngSwitchDefault can be placed anywhere inside the container
element and not necessarily at the bottom. If you add more than one
ngSwitchDefault directive, all of them are displayed.
Any elements placed inside the container element, but outside the
ngSwitchCase or ngSwitchDefault elements are displayed as it is.
1. class item {
2. name: string;
3. val: number;
4. }
5. export class AppComponent
6. {
7. items: item[] = [{name: 'One', val: 1}, {name: 'Two', val: 2}, {name: 'Three', val:
3}];
8. selectedValue: string= 'One';
9. }
1. <select [(ngModel)]="selectedValue">
2. <option *ngFor="let item of items;" [value]="item.name">{{item.name}}</
option>
3. </select>
4. <div class='row' [ngSwitch]="selectedValue">
5. <div *ngSwitchCase="'One'">One is Pressed</div>
6. <div *ngSwitchCase="'Two'">Two is Selected</div>
16
7. <div *ngSwitchDefault>Default Option</div>
8. </div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title: string = 'ngIf Example' ;
showMe: boolean;
}
===============================
<div class="row">
Show <input type="checkbox" [(ngModel)]="showMe" />
</div>
<h1>ngIf </h1>
<p *ngIf="showMe">
ShowMe is checked
</p>
<p *ngIf="!showMe">
ShowMe is unchecked
</p>
<h1>ngIf Else</h1>
17
<ng-template #elseBlock1>
<p>ShowMe is unchecked Using elseBlock</p>
</ng-template>
<ng-template #thenBlock2>
<p>ShowMe is checked Using thenblock</p>
</ng-template>
<ng-template #elseBlock2>
<p>ShowMe is unchecked Using elseBlock</p>
</ng-template>
<p [hidden]="showMe">
content to render, when the condition is true using hidden property
binding
</p>
<p [hidden]="!showMe">
content to render, when the condition is false. using hidden property
binding
</p>
Data binding can be either one-way data binding or two-way data binding.
18
One-way databinding
One way databinding is a simple one way communication where HTML
template is changed when we make changes in TypeScript code.
Or
In one-way databinding, the value of the Model is used in the View (HTML
page) but you can't update Model from the View. Angular Interpolation /
String Interpolation, Property Binding, and Event Binding are the example of
one-way databinding.
Two-way databinding
In two-way databinding, automatic synchronization of data happens between
the Model and the View. Here, change is reflected in both components.
Whenever you make changes in the Model, it will be reflected in the View
and when you make changes in View, it will be reflected in Model.
Angular provides four types of data binding and they are different on the way
of data flowing.
o String Interpolation
o Property Binding
o Event Binding
o Two-way binding
19
String interpolation
String Interpolation is a one-way databinding technique which is used to
output the data from a TypeScript code to HTML template (view). It uses the
template expression in double curly braces to display the data from the
component to the view.
For example:
{{ data }}
Syntax:
Property Binding
Property Binding is also a one-way data binding technique. In property
binding, we bind a property of a DOM element to a field which is a defined
property in our component TypeScript code.
For example:
<img [src]="imgUrl"/>
Syntax:
20
title = "Data binding using Property Binding";
imgUrl="https://static.angular.com/tutorial/angular7/images/angular-7-
logo.png";
Event Binding
In Angular , event binding is used to handle the events raised from the DOM
like button click, mouse move etc. When the DOM event happens (eg. click,
change, keyup), it calls the specified method in the component. In the
following example, the cookBacon() method from the component is called
when the button is clicked:
For example:
1. <button (click)="cookBacon()"></button>
21
In two way data binding, property binding and event binding are combined
together.
Syntax:
Note: For two way data binding, we have to enable the ngModel directive. It depends upon
FormsModule in angular/forms package, so we have to add FormsModule in imports[] array
in the AppModule.
In two way data binding, property binding and event binding are
combined together.
Syntax:
1. [(ngModel)] = "[property of your component]"
22
Note: For two way data binding, we have to enable the ngModel directive. It depends upon
FormsModule in angular/forms package, so we have to add FormsModule in imports[] array
in the AppModule.
Open your project's app.module.ts file and use the following code:
23
app.component.ts file:
24
app.component.html file:
25
Now, start your server and open local host browser to see the result.
Output:
26
You can check it by changing textbox value and it will be updated in
component as well.
For example:
27
Property Binding in Angular
Property Binding is also a one-way data binding technique. In property
binding, we bind a property of a DOM element to a field which is a defined
property in our component TypeScript code. Actually Angular internally
converts string interpolation into property binding.
For example:
Note: String Interpolation and Property binding both are one-way binding. Means, if field
value in the component changes, Angular will automatically update the DOM. But any
changes in the DOM will not be reflected back in the component.
28
Now, open app.component.html and use the following code for property
binding:
29
Run the ng serve command and open local host to see the result.
Output:
30
component to the view. String interpolation adds the value of a property
from the component.
For example:
{{ data }}
Open app.component.ts file and use the following code within the file:
31
Now, open app.component.html and use the following code to see string
interpolation.
1. <h2>
2. {{ title }}
3. </h2>
32
Now, open Node.js command prompt and run the ng serve command to see
the result.
Output:
33
String Interpolation can be used to resolve some other expressions too. Let's
see an example.
Example:
Update the app.component.ts file with the following code:
app.component.html:
34
Output:
App.component.ts:
35
App.component.html:
36
For example:
1. <button (click)="cookBacon()"></button>
Now, open the app.component.ts file and use the following code:
37
app.component.html:
38
Output:
39
Click on the "Save" button and open console to see result.
Event Bubbling
Event bubbling is used to specify an order in which event handlers are called
when one element is nested inside a second element, and both elements
have registered a listener for the same event (i.e. click).
Let's see the above button example. Here, I have used a div wrapper around
the button in component HTML and div has also a click event handler. It is
only to show some message if div is clicked.
40
12. console.log("DIV is clicked!");
13. }
14.}
app.component.html:
41
Output:
42
Here, you can see that your div message is also occurred. This is all due to
event bubbling where you have specified onDivClick button.
43
Output:
Angular Forms
Angular forms are used to handle user's input. We can use Angular form in
our application to enable users to log in, to update profile, to enter
information, and to perform many other data-entry tasks.
o Reactive forms
o Template-driven forms
Both approaches are used to collect user input events from the view,
validate the user input, create a form model and data model to update, and
provide a way to track changes.
44
Reactive Forms
o Reactive forms are more robust.
o Reactive forms are more scalable, reusable, and testable.
o They are most preferred to use if forms are a key part of your application, or
your application is already built using reactive patterns. In both cases,
reactive forms are best to use.
Template-driven Forms
o Template-driven forms are best if you want to add a simple form to your
application. For example: email list signup form.
o Template-driven forms are easy to use in the application but they are not as
scalable as Reactive forms.
o Template-driven forms are mainly used if your application's requires a very
basic form and logic. It can easily be managed in a template.
o Create an Angular form app named angularfrom and run the server by
using the following commands.
1. ng new angularform
2. cd angularform
3. ng serve
45
o Install the Bootstrap 4 using the following command.
46
1. npm install bootstrap --save
Now, include the bootstrap 4 inside the angular.json file inside styles array.
1. "styles": [
2. "./node_modules/bootstrap/dist/css/bootstrap.min.css",
3. "src/styles.css"
4. ],
1. // app.module.ts
2. import { BrowserModule } from '@angular/platform-browser';
3. import { NgModule } from '@angular/core';
4.
5. import { AppRoutingModule } from './app-routing.module';
6. import { AppComponent } from './app.component';
7. import { ReactiveFormsModule } from '@angular/forms';
8.
47
9. @NgModule({
10. declarations: [
11. AppComponent
12. ],
13. imports: [
14. BrowserModule,
15. AppRoutingModule,
16. ReactiveFormsModule
17. ],
18. providers: [],
19. bootstrap: [AppComponent],
20.})
21.export class AppModule { }
48
o Add FormControl class register the control into the template and update the
FormControl value
The FormControl class is the fundamental building block when using the
reactive forms. So if you want to register the single form control, you need to
import the FormControl class into your component and create the new
instance of a form control to save as the class property.
1. // app.component.ts
2. import { Component } from '@angular/core';
3. import { FormControl } from '@angular/forms';
4. @Component({
5. selector: 'app-root',
6. templateUrl: './app.component.html',
7. styleUrls: ['./app.component.css']
8. })
9. export class AppComponent {
10. email = new FormControl('');
11. updateEmail() {
12. this.email.setValue('[email protected]');
13. }
14.}
49
Also, update the view app.component.html file.
1. <div class="container">
2. <div class="form-group">
3. <label>
4. Email:
5. </label>
6. <input type="text" [formControl]="email" />
7. </div>
8. <div class="form-group">
9. <button (click)="updateEmail()" class="btn btn-dark">Update Email</button>
10. </div>
11. <p>
12. Value: {{ email.value }}
50
13. </p>
14.</div>
Output:
Enter any email id and you will see the result in the value.
51
When you click on the "Update Email" button, it will update the email id as
we saved in the template file.
Angular vs React
52
Angular and React both are related to JavaScript but there are a lot of
differences between them. Here, we are going to compare both of them and
also explain their similarities, differences, advantages and disadvantages
etc.
Architectur Angular is a full MVC (Model, View, and React is a simple JavaScript libra
e Controller) framework. (just the View) but it gives you mu
Angular is considered a framework more freedom. React facilitates y
because it provides strong facilities like to choose your own librari
how to structure your application. In Most prominent features of React:
Angular, you don't need to decide routing
libraries. o React uses JSX, an XML-l
Most prominent features of Angular: language built on top
JavaScript instead of clas
o Provides templates, based on an
templates.
extended version of HTML.
o XSS protection.
o Provides XSS protection.
o No dependency injection.
o Provides Dependency injection.
o Fetch for Ajax requests.
o Provides Ajax requests by
@angular/HTTP. o Utilities for unit-testi
components.
o @angular/router for Routing.
53
React also provides some popu
o Component CSS encapsulation. libraries to add functionalities:
o Utilities for unit-testing components. o React-router for routing.
o @angular/forms for building forms. o Redux or MobX for sta
management.
o Enzyme for additional testi
utilities.
Used DOM Angular uses regular DOM. The regular React uses virtual DOM wh
DOM updates the entire tree structure of makes it amazing fast. It was s
HTML tags. It doesn't make difference in a the most prominent feature of Rea
simple real app but if you are dealing with when it was release
large amount of data requests on the same It updates only the specific part with
page (and the HTML block is replaced for a block of HTML codes. The virtu
every page request), it affects the DOM looks only at the differenc
performance as well as the user's between the previous and curre
experience. HTML and changes only that p
which is required to be updated.
Used Angular uses enhanced HTML templates React uses UI templates and inli
Templates with Angular directives i.e. "ng-if" or "ng- JavaScript logic together which w
for" etc. It is quite difficult because you not done by any company befo
have to learn its specific syntax. This is called JSX. React us
component which contains both t
markup AND logic in the same fi
React also uses an XML-like langua
which facilitates developers to wr
markup directly in their JavaScr
code. JSX is a big advantage
development, because you ha
everything in one place, and co
completion and compile-time chec
work better.
Data Angular provides two-way data binding. React provides one-way data bindin
Binding When you change the model state, then In React first the model state
the UI element changes. In Angular, if you updated, and then it renders t
change the UI element, then the change in the UI element. When y
corresponding model state changes as change the UI element, the mod
54
well. Additionally, if you change the model state does not change.
state, then the UI element changes.
Size The size of Angular is large, so it takes The size of React is smaller th
longer load time and performance on Angular, so it is a little bit faster.
mobile.
Company
o Google o Facebook
Using
o Nike o Airbnb
o Forbes o Uber
o Upwork o Netflix
o General Motors o Instagram
o HBO o WhatsApp
o Sony etc. o Dropbox etc.
Similarities
o Angular and React both are available under MIT license.
o Both Angular and React are component based.
55
Angular Pipes
In Angular 1, filters are used which are later called Pipes onwards Angular2.
In Angular 7, it is known as pipe and used to transform data. It is denoted by
symbol |
Syntax:
1. {{title | uppercase}}
Pipe takes integers, strings, arrays, and date as input separated with |. It
transforms the data in the format as required and displays the same in the
browser.
Let's see an example using pipes. Here, we display the title text in upper and
lower case by using pipes.
Example:
Define a variable named "title" in component.ts file.
1. <h1>
2. {{ title | uppercase }} <br/></h1>
3. <h1>
4. {{ title | lowercase }} <br/></h1>
56
Output:
Run ng serve and see the result. You will see the following result.
Here, you can see that pipes have changed the tittle in upper and lowercase.
o Lowercasepipe
o Uppercasepipe
o Datepipe
o Currencypipe
o Jsonpipe
o Percentpipe
o Decimalpipe
o Slicepipe
57
You have seen the lowercasepipe and uppercasepipe examples. Now, let's
take some examples to see how the other pipes work.
Example:
Define the required variables in component.ts file.
component.ts file:
component.html file:
58
9. <b>{{659.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign
of the currency.
10. <h1>Date pipe</h1>
11. <b>{{todaydate | date:'d/M/y'}}</b><br/>
12. <b>{{todaydate | date:'shortTime'}}</b>
13. <h1>Decimal Pipe</h1>
14. <b>{{ 454.77714 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for i
ntegers to be displayed.
15. </div>
16. <div style = "width:40%;float:left;border:solid 1px black;">
17. <h1>Json Pipe</h1>
18. <b>{{ jsonval | json }}</b>
19. <h1>Percent Pipe</h1>
20. <b>{{00.54565 | percent}}</b>
21. <h1>Slice Pipe</h1>
22. <b>{{months | slice:2:6}}</b>
23. // here 2 and 6 refers to the start and the end index
24. </div>
25.</div>
Output:
59
How to create a custom pipe?
To create a custom pipe, create a new ts file and use the code according to
the work you have to do. You have to import Pipe, PipeTransform from
Angular/Core. Let's create a sqrt custom pipe.
sq.pipe.ts file:
60
7. return Math.sqrt(val);
8. }
9. }
app.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Welcome Custom Pipes';
}
Now, it's turn to make changes in the app.module.ts. Create a class named
as SqPipe. This class will implement the PipeTransform. The transform
method defined in the class will take argument as the number and will return
the number after taking the square root.
As, we have created a new file so, we need to add the same in
app.module.ts.
Module.ts file:
61
12. ],
13. providers: [],
14. bootstrap: [AppComponent]
15.})
16.export class AppModule { }
component.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<h1>Example Of custom Pipe</h1>
<b>Square root of 625 is {{625 | sq}}</b><br>
<b>Square root of 169 is {{169 | sq}}</b>
</div>
</body>
</html>
Output:
62
frameworks like Angular or React for presenting and manipulating data
efficiently. Updated Angular is much more efficient compared to the older
version of Angular, especially core functionality was moved to different
modules. That’s why it becomes so much fast and smooth compare to the
older one. Newly added angular CLI. With that package, you can create
scaffolding of your Angular project
Architecture:
63