0% found this document useful (0 votes)
28 views

Angular

The document discusses: 1) Creating an Angular project using the Angular CLI and serving it locally. 2) Defining a component with TypeScript decorators and accessing its properties in the template. 3) Using built-in directives like *ngFor to loop through and display data. 4) Adding conditional logic with *ngIf to check for empty lists before displaying data.

Uploaded by

bitztool
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Angular

The document discusses: 1) Creating an Angular project using the Angular CLI and serving it locally. 2) Defining a component with TypeScript decorators and accessing its properties in the template. 3) Using built-in directives like *ngFor to loop through and display data. 4) Adding conditional logic with *ngIf to check for empty lists before displaying data.

Uploaded by

bitztool
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Angular

CLI: npm install -g @angular/cli –global


ng version
Let’s start by creating
ng new my-first-project In app.component.ts, title is defined that is directly used in
app.component.html as {{ title }}
Router is built-in feature of Angular.

Name of the project can be created as above


In app.component.ts file @Component is a decorator
Angular uses typescript
Tells angular that how component will be going to use this selector which
is a tag name

cd my-first-project templateUrl tells where is the template

ng serve styleUrls tells where is the styling

main.ts is the main file The app-root is already in the index.html page.

Component is a building block So complete component (app-root) will be injected into the index.html
page with the provided template and styling
Data
As we write application for consuming data, let’s start it by In src, create a folder shared/models.
writing:
Create a file in models: wishItem.ts

Everything should be an exported module, so we can import it into other


ng new wishlist file.

cd wishlist Public means it can be accessed outside of a class.

ng serve Write the basic code with two public available variables and import it into
the app.component.ts.

Create a new item in AppComponent as WishItem constructor.


Now we’ll write a class that will represent a wish.
Hover on it, it says that it accepts two items, the same as we created in the
constructor
export class AppComponent { To display the items into the template, open app.component.html.

item = [ Import bootstrap library into the index.html for a better display
new WishItem('Learn Javascript',
false),
Remove completely all the things as first line says!
new WishItem('Learn Angular',
true), Update it with:

new WishItem('Learn Vue', true),


<div class="container">
];
<div>
title = 'wishlist';
{{item[0].wishText}}
}
</div>
</div>
Updated AppComponent in
app.component.ts
Directives AngularJS directives are extended HTML attributes with the prefix ng-.

*ngFor is a directive to traverse over an array object and display the data in
the UI
Directives are classes that add additional
behavior to elements in your Angular friendslist = [
applications. Use Angular's built-in directives { name: 'John Doe', age: 25 }, { name: 'Jane
to manage forms, lists, styles, and what users
Doe', age: 45 }
see
];
<ul>
AngularJS lets you extend HTML with new
attributes called Directives. <li *ngFor="let item of friendslist">

{{ item.name }} is {{ item.age }} years old


AngularJS has a set of built-in directives
which offers functionality to your applications. </li></ul>

AngularJS also lets you define your own ngFor is a structural directive as it changes the DOM
structure
directives.
<div class="container"> <div class="container">
<ul class="wish-list"> <ul class="wish-list">
<li *ngFor="let item of item"> <li *ngFor="let item of item">
{{item.wishText}} <div class="form-check">
</li> <label class="form-check-label">
</ul> <input class="checkbox"
</div> type="checkbox"> {{item.wishText}}
</label>
ngFor directive </div>
let item of item value of the directive is </li>
javascript expression </ul>
</div>
Just like the loop in JS:

for (let item of items) { Add the form checkbox to the code

} ngFor adds item into the DOM structure


Update css in app.component.css <div class="container">
Add the following: <ul class="wish-list">
<li *ngFor="let item of item">
.wish-list {
<div class="form-check">
list-style: none;
<label class="form-check-label">
}
<input class="checkbox" type="checkbox">
Wish-list the class defined in ul of
{{item.wishText}}
app.component.html
</label>
</div>
</li>
</ul>
</div>

Add the form checkbox to the code


Comment the lines in app.component.ts Now hover on the item array it says any, means
it can contain anything.
new WishItem('Learn Javascript',
false), To resolve it more typescript wise is; as it
contains only the items from WishItem object
new WishItem('Learn Angular',
therefore:
true),
new WishItem('Learn Vue', true), item: WishItem[] = []
item it is the property variable name
Hover on the item array and it says WishItem[] it is the type of the variable or
never, that is due to TypeScript. property, which is an array
To resolve it, we can use type any.
item:any = []
Directives <element ngIf="expression"></element>

An expression that will completely remove the element if it returns false. If


The ng-if directive removes the HTML it returns true, a copy of the element will be inserted instead.
element if the expression evaluates to
false.
export class AppComponent {
If the if statement evaluates to true, a
myBool = true;
copy of the Element is added in the DOM.
}
The ng-if directive is different from the
ng-hide, which hides the display of the
<div *ngIf = 'myBool'>Boolean is set to
element, where the ng-if directive
true</div>
completely removes the element from the
DOM.
Directives <element ngIf="expression"></element>

An expression that will completely remove the element if it returns false. If


The ng-if directive removes the HTML it returns true, a copy of the element will be inserted instead.
element if the expression evaluates to
false.
export class AppComponent {
If the if statement evaluates to true, a
myBool = true;
copy of the Element is added in the DOM.
}
The ng-if directive is different from the
ng-hide, which hides the display of the
<div *ngIf = 'myBool'>Boolean is set to
element, where the ng-if directive
true</div>
completely removes the element from the
DOM.
Just add the following into the <div class="container">
<div *ngIf="item.length === 0; else showItems">
app.component.html:
There are no wishes to display.
<div *ngIf="item.length === 0;">
</div>
There are no wishes to display.
<ng-template #showItems>
</div> <ul class="wish-list">
<li *ngFor="let item of item; index as ii">

The below div will be rendered as there <div class="form-check">


<label class="form-check-label">
is no condition on below div.
<input
class="checkbox"
We can:
type="checkbox"
<ul *ngIf="item.length !== 0;" [checked]="item.isComplete"
class="wish-list"> [attr.data-index]="ii"
> {{item.wishText}}
</label>
After doing the following code, try
</div>
commenting the items from
</li>
app.component.ts. </ul>
</ng-template>
</div>
Directives <div class="list" *ngIf="list.length else emptyList">
<ul>
<li *ngFor="let item of list">{{item.name}}</li>
</ul>
As the name suggests the <ng-
</div>
template> is a template element that
Angular uses with structural <ng-template #emptyList>
directives (*ngIf, *ngFor, [ngSwitch] <div>Sorry, The list is empty</div>
and custom directives). </ng-template>

<!-- OR Another more elaborate syntax-->


<ng-template [ngIf]="list.length" [ngIfElse]="emptyList">
These template elements only work in <ul>
<ng-template ngFor let-item [ngForOf]="list">
the presence of structural directives
<li>{{item.name}}</li>
</ng-template>
list = [ </ul>
{ id: 1, name: "Angular" }, </ng-template>

{ id: 2, name: "React" },


<ng-template #emptyList>
{ id: 3, name: "Vue" } <div>Sorry, The list is empty</div>
]; </ng-template>
Both are same
<div class="container">
<div class="container">
<div *ngIf="item.length === 0; then noItems else
showItems"></div>
<div *ngIf="item.length === 0; else showItems">
<ng-template #noItems>
There are no wishes to display.
There are no wishes to display.
</div>
</ng-template>
<ng-template #showItems>
<ng-template #showItems>
<ul class="wish-list">
<ul class="wish-list">
<li *ngFor="let item of item; index as ii">
<li *ngFor="let item of item; index as ii">
<div class="form-check">
<div class="form-check">
<label class="form-check-label"> <input
<label class="form-check-label"> <input
class="checkbox" type="checkbox" [checked]="item.isComplete"
class="checkbox" type="checkbox"
[attr.data-index]="ii" > {{item.wishText}} </label>
[checked]="item.isComplete" [attr.data-index]="ii" >
</div>
{{item.wishText}} </label>
</li>
</div>
</ul>
</li>
</ng-template>
</ul>
</div>
</ng-template>
</div>
Directive Types

Structural directives Components are the main Attribute directives change


change the DOM layout by building blocks for Angular the appearance or behavior
adding and removing DOM applications. Each of an element, component,
elements component consists of: or another directive
● An HTML template that
NgIf > Conditionally
creates or disposes of declares what renders
subviews from the template. on the page NgClass > Adds and removes
● A TypeScript class a set of CSS classes.
NgFor > Repeat a node for that defines behavior
each item in a list. ● A CSS selector that NgStyle > Adds and removes
defines how the a set of HTML styles.
NgSwitch > A set of component is used in a
directives that switch template NgModel > Adds two-way data
among alternative views. ● Optionally, CSS styles binding to an HTML form
applied to the element.
template
export class WishItem { When we want to bind something to the
constructor(public wishText : string,
javascript property of an object, we can
public isComplete : boolean = false) {}
surround it into the square bracket:
}

We can also assign a default value to In app.component.html


[checked]="item.isComplete"
a class item.
We are assigning the javascript expression to the
property using "item.isComplete"

Javascript uses camelCase to use the html


property like in colSpan

We cannot have two structural directives on the


same element We can get the index by using:
<li *ngFor="let item of item; index as ii">

<li *ngIf="True" *ngFor="let item of item; [attr.data-index]="ii"

index as ii">
Events We bind the events same as we were binding the
properties, instead we will be using
parenthesis().
How the user interact with the Just add the () and see the complete list of
application. available events.

In out application user can click the Name of events are all lowercase.
checkbox to toggle it.
(click)="" // Can be a function or js expression
We’ve bound the isComplete property
to the [checked]. This is one-way
(click)="toggleItem()" //this will be a method
binding. We are taking the value of
isComplete and binding it to the into our component class.
checked property of the checkbox.
Add the following method under the title in
app.component.ts and see the console

To toggle the checkbox we’ve to toggleItem = () => {


update the isComplete property. console.log("CLICKED")
}
Events We can update the property:
toggleItem = (item: WishItem) => {
We can access the event by: item.isComplete = !item.isComplete;
console.log(item)
(click)="toggleItem($event)" }
This will pass the event object to Now see the console. Property is updated.
the function

Update the function as


toggleItem = (e: any) => {
console.log(e)
}

Update the function as


toggleItem = (item: WishItem) => {
console.log(item)
}
Template Driven <form class="row mt-3 gx-3 gy-2 align-items-
center justify-content-center">
<div class="col-sm-6">
Angular have two ways to work with
<label class="visually-hidden"
forms:
for="specificSizeInputName">Wish</label>
Reactive Forms - more scalable
<input type="text" name="new-wish-text"
Template Driven forms - rely on
class="form-control">
directives </div>
<div class="col-auto">
Add it into the html. <button
"$event.preventDefault()" type="submit"
Prevent the form to submit class="btn btn-primary"
We can have multiple expression
(click)="$event.preventDefault();
addNewWish() "
>Add Wish</button>
</div>
</form>
Template Driven Open app.module.ts
This file defines everything that our component

<input type="text" name="new-wish-text" requires in order to run.


class="form-control" @NgModule({ declarations: [ AppComponent ],
[(ngModel)]="newWishText"> imports: [ BrowserModule ], providers: [],
bootstrap: [AppComponent] })
The ng-model directive binds an HTML
form element to a variable in the declarations: set of components or directives that

scope. If the variable does not exist belong to the app module

in the scope, it will be created imports: things available to the templates inside
app module
providers: objects that can be injected for the
newWishText = '';
module
Add it into the components file
Bootstrap: entry point of the module, it is our
AppModule

In imports add: FormsModule


Template Driven In component remove the wishes:
item: WishItem[] = [
// new WishItem('Learn Javascript'),
Update the function
// new WishItem('Learn Angular', true),
addNewWish = () => {
// new WishItem('Learn Vue', true),
// Will add new wish
];
// clear the text box
this.item.push(new
In html:
WishItem(this.newWishText))
<div class="row mt-3">
this.newWishText = ''
// Add all the below code in here for spacing
} </div>
<div class="row mt-3">
<div class="col-sm-2"> Add the code into our html below the input field
<select Create a property under newWishText as:
class="form-select" listFilter: String = '0';
[(ngModel)]="listFilter" visibleItems: WishItem[] = this.item;

(ngModelChange)="filterChanged($event Create the function into the component like we


)"> were doing.
<option
value="0">All</option> ngModelChange: event occurs only if the model
<option changes, only with the ngModel. It contains the
value="1">Unfulfilled</option> new value
<option
value="2">Fulfilled</option> In components add:
</select> filterChanged = (value: any) => {
</div> console.log(value)
</div> }
See the console
Update the function: Replace items with visibleItems as:
filterChanged(value: any) { <div *ngIf="visibleItems.length === 0; else
if (value === '0') { showItems">
this.visibleItems = this.item; <li *ngFor="let item of visibleItems; index as
} else if (value === '1') { ii">
this.visibleItems =
this.item.filter(i => !i.isComplete);
} else {
this.visibleItems =
this.item.filter(i => i.isComplete);
}
}
Getters Remove the filterChanged and ngModelChanged and
update the visible item property to:
get visibleItems(): WishItem[] {
Try to toggle the checkbox, on
let value = this.listFilter;
runtime it is not displaying that
if (value === '0') {
particular wish in the respective
return this.item;
filter unless we choose the filter.
} else if (value === '1') {
return this.item.filter(i => !i.isComplete);
The get syntax binds an object
} else {
property to a function that will be
return this.item.filter(i => i.isComplete);
called when that property is looked
}
up
};

Now we are able to solve it.


ANGULAR Path:
> Installation
> Node/ NPM
Development platform to build UI part
> Typescript
of the application
> Angular
Platform means it provide libraries,
component based well-structured
Create project using: ng new project-name
framework and tools
ng serve will launch the project
There is Routing, forms, HttpClient
etc.
Spec files are related to unit testing
Focuses on UI part of the application
Reusable libraries as we discussed

It has developer tools:


https://chromewebstore.google.com/
detail/angular-devtools/
ienfalfjdbdpebioblfackkekamfmbnh?
pli=1
NodeJS So V8 engine if installed in case of us NODEJS so
we can run JS outside the browser

JS runtime built on V8 Engine (high-


Create a file with some variables and run using
performance JavaScript and
node from VSCODE.
WebAssembly engine)

V8 take JS and generates byte code


from syntax which is compiled to
machine code therefore named after 8
cylinder engine, therefore it is a
super-fast compiler

NodeJS created a separate setup or


maybe a wrapper from V8 engine.
NPM TypeScript npm install typescript -g
Helps to install JS packages tsc -v //(check version)
e.g. npm install jquery Strongly typed syntax for types

So it will fetch the complete source Normal JS doesnot care about the
code as well as compiled js files datatypes
from github E.g
let x = 0
Package.json has list of dependencies x = “Nothing”
that are installed as node_modules in it identifies itself and js does not
project folder complains about it

So in strongly typed typescript, we


cannot change type of any defined
variable. So datatype is not allowed
to be changed
TypeScript run using: tsc filename

It will compile both of the files


//File 1 Final version will be Javascript files
Import {Address} from “./file2”
class User { tsc init will generate config file for typescript
name:string = ‘’;
code:string = ‘’; Just type tsc and it will generate all the files.
Address:Array<Address> = null; We can make sure output should be in any
} particular directory. “outDir”
class Customer extends User {
} Now update this to:
Address:Array<Address> = new Array<Address>();
//File 2
export class Address { So the newly tsconfig file is now having a check
name:string = ‘’; and control of everything as it is the
} configuration file
Vocab ● Bootstrap is a way to initialize and
launch an application or system
● Decorator that appears immediately before
● Html component having directives are known
a class definition, which declares the
as angular templates
class to be of the given type, and
● Component comprises of logic and view
provides metadata suitable to the type
● Selector in app.component file helps to
○ @Component()
call the component so it is the name of the
○ @Directive()
component
○ @Pipe()
● If any angular syntax is written inside the
○ @Injectable()
html it is a directive
○ @NgModule()
● Data binding is a process that allows
● @Component is a decorator which makes the
applications to display data values to a
AppComponent a component
user and respond to user actions. User
● Directive is a class that can modify the
actions include clicks, touches,
structure of the DOM or modify attributes
keystrokes, etc.
in the DOM and component data model
● Binding is the practice of setting a
● Module is logically grouping components
variable or property to a data value
Modules ● Bootstrap is a way to initialize and
launch an application or system
● Decorator that appears immediately before
● Angular apps are modular and this
a class definition, which declares the
modularity system is called as NgModules.
class to be of the given type, and
See it in the app.module.ts file NgModule
provides metadata suitable to the type
● Module in Angular refers to a place where
○ @Component()
you can group the components, directives,
○ @Directive()
pipes, and services, which are related to
○ @Pipe()
the application.
○ @Injectable()
● They can import functionality that is
○ @NgModule()
exported from other NgModules, and export
● @Component is a decorator which makes the
selected
AppComponent a component
● Every Angular application has at least one
● Directive is a class that can modify the
NgModule class, the root module, which is
structure of the DOM or modify attributes
conventionally named AppModule.
in the DOM and component data model
● Module is logically grouping components
Index.html

Bootstrapping is a technique of initializing or loading angular


3rd party app:
● Index.html
● 3rd party libs and application loads
● Main.ts is the app entry point
main.ts ● Root module
● Root component
● Template
app.module.ts

Takes up the html, css and logic and runs as per the selector, <app-
app.component root> and this complete module will be injected into index.html
.ts
Component comprises Module1 Main.ts
of view(html) and logic app.module.ts Which module should run first
View and logic are
connected by
templateUrl in
app.component.ts
Inside the views we
have directives i.e.
Component2 Component3
View (html) + View (html) +
events (click). Logic(ts) Logic(ts)
templateUrl templateUrl Module2
Module is the grouping Component1 app.module.ts
of multiple View (html) +
Logic(ts)
components templateUrl

We can have multiple


modules having other Component is app.component.ts and Component5 Component6
app.component.html. View (html) + View (html) +
logical group of
Logic(ts) Logic(ts)
components templateUrl templateUrl
First UI to run is index.html which will run
the main.ts that will call the module. Component4
Which module should View (html) +
run first, is defined in In side module we have the bootstrap that Logic(ts)
main.ts. will run the first component which will be templateUrl
loaded inside index.html using the
selector i.e. <app-root></app-root>.
Binding
Round brackets: The data can go back to the
Bind an input element to a variable of a component with the help of events.
component. So for binding we have
ngModel. So for two-way data-bind we will be using [()]
ngModel=”variableName” // defined into both type of brackets.
our logic
For showing the value of someVariableValue we can
<input type=”text” use the expression {{ someVariableValue }} i.e.
[(ngModel)]=”someVariableValue” /> value into the double curly braces
Above example is two way data-binding. Expression can also be named as Interpolation.
Interpolation means mixing html with angular
Square brackets: Data can come to the UI
from the component. Whenever the For ngModel we have to import FormsModule in the
someVariableValue changes it will be imports section of app.module.ts
passed to the UI
Recap directives
Round brackets: The data can go back to the
Structural directives add remove elements component with the help of events.
from DOM means changes the DOM layout
e.g. *ngFor, *ngIf So for two-way data-bind we will be using [()]
It is denoted by * both type of brackets.

Attribute directive change the behavior For showing the value of someVariableValue we can
or appearance of the existing element use the expression {{ someVariableValue }} i.e.
e.g. ngModel, (click) value into the double curly braces
Expression can also be named as Interpolation.
Component directive where we call or Interpolation means mixing html with angular
create the component e.g. <app-root>.
For ngModel we have to import FormsModule in the
imports section of app.module.ts
Component creation <div *ngIf="visibleItems.length === 0; else showItems">
There are no wishes to display.
</div>
We can create component manually but there <ng-template #showItems>
will be list of steps. We need to update <ul class="wish-list">
module file, create code files and different <li *ngFor="let item of visibleItems; index as ii">
imports. <div class="form-check">
<label class="form-check-label"> <input
For that Angular CLI is a help. class="checkbox" type="checkbox" [checked]="item.isComplete"
[attr.data-index]="ii" (click)="toggleItem(item)" >
{{item.wishText}} </label>
ng generate component wish-list
</div>
</li>
It will create same hierarchy and files under
</ul>
app.
</ng-template>

See the last line in console, it will update the


app.module.ts file. It will add the module in Remove these lines and add it into the wish-list-
app declaration: component.html file.

CREATE src/app/wish-list/wish-list.component.css (0 bytes) Copy the toggleItem function into the component file and
CREATE src/app/wish-list/wish-list.component.html (24 bytes) import it
CREATE src/app/wish-list/wish-list.component.spec.ts (574 bytes)
CREATE src/app/wish-list/wish-list.component.ts (213 bytes)
Component name should be as defined into the selector
UPDATE src/app/app.module.ts (471 bytes)
Component creation <div *ngIf="visibleItems.length === 0; else showItems">
There are no wishes to display.
</div>
We can create component manually but there <ng-template #showItems>
will be list of steps. We need to update <ul class="wish-list">
module file, create code files and different <li *ngFor="let item of visibleItems; index as ii">
imports. <div class="form-check">
<label class="form-check-label"> <input
For that Angular CLI is a help. class="checkbox" type="checkbox" [checked]="item.isComplete"
[attr.data-index]="ii" (click)="toggleItem(item)" >
{{item.wishText}} </label>
ng generate component wish-list
</div>
</li>
It will create same hierarchy and files under
</ul>
app.
</ng-template>

See the last line in console, it will update the


app.module.ts file. It will add the module in Remove these lines and add it into the wish-list-
app declaration: component.html file.

CREATE src/app/wish-list/wish-list.component.css (0 bytes) Copy the toggleItem function into the component file and
CREATE src/app/wish-list/wish-list.component.html (24 bytes) import it
CREATE src/app/wish-list/wish-list.component.spec.ts (574 bytes)
CREATE src/app/wish-list/wish-list.component.ts (213 bytes)
Component name should be as defined into the selector
UPDATE src/app/app.module.ts (471 bytes)
Component creation <form class="row mt-3 gx-3 gy-2 align-items-center justify-
content-center">
<div class="col-sm-6">
Create a new component add-wish-form <label class="visually-hidden"
for="specificSizeInputName">Wish</label>
Update the files
<input type="text" name="new-wish-text" class="form-
control" [(ngModel)]="newWishText">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary"
(click)="$event.preventDefault(); addNewWish()" >Add
Wish</button>
</div>
</form>
newWishText = '';
addNewWish = () => {
this.item.push(new WishItem(this.newWishText))
this.newWishText = ''
}
Event Emitter We can implement it with the utilization
of the @Output() decorator and the
EventEmitter class. The emitted event can
EventEmitter enables components to
be listened to by the parent component
communicate with each other
through the use of the @Input() decorator.
The sending of an event is done through
the EventEmitter.emit() method.
Custom events are emitted from a
child component to its parent
component through the use of
EventEmitter

For instance, when a button on a


child component is clicked, the
child component employs an
EventEmitter to inform the parent
component of the button click
Lifecycle Hooks
Angular provides a set of
lifecycle hooks that allow
developers to tap into various
stages of a component's life
cycle.

These hooks provide the ability to


perform actions at specific points
in the component's creation,
rendering, and destruction
process.
Lifecycle Hooks
ngOnChanges: When an input/output binding value
changes

ngOnInit: After the first ngOnChanges

ngDoCheck: Developer’s custom change detection

ngAfterContentInit: After component content


initialized

ngAfterContentChecked: After every check of


component content

ngAfterViewInit: After a component’s views are


initialized

ngAfterViewChecked: After every check of a


component’s views

ngOnDestroy: Just before the component/directive is


destroyed
ngOnInit ngOnInit: This hook is called once when the
component is initialized.

ngOnInit() executes once when a import { Component, OnInit } from '@angular/core';

component is initialized.
@Component({

ngOnInit() executes after data-bound selector: 'app-root',


template: '<p>{{ message }}</p>',
properties are displayed and input
})
properties are set.
export class AppComponent implements OnInit {

ngOnInit() executes once after the first message: string = '';

ngOnChanges.
ngOnInit() {
ngOnInit() will still execute regardless this.message = 'Component initialized!';
of whether or not implements OnInit is
}
included in the class definition.
}
import { Component, OnInit } from "@angular/core";

ngOnInit @Component({
selector: "app-root",
template:
ngOnInit is called after the constructor "<div><h1>{{data}}</h1><h1>{{subtitle}}</h1></div>",
is called and after the component’s styles: [`div {
inputs have been initialized
color: green;
}`],
ngOnInit is commonly used to call
services or to set up subscriptions })
export class AppComponent {
title: string;
subtitle: string;
data: string;
constructor() {
this.title = "Welcome to Angular";
this.subtitle = "Welcome to Angular";
this.data = "Welcome to Angular";
}
ngOnInit() {
this.data = "data - from ngOnInit";
this.subtitle = "subtitle - from ngOnInit";
}
Difference between constructor and ngOnInit in Angular:
import { Component, DoCheck } from
ngDoCheck '@angular/core';

@Component({
selector: 'app-example',
This hook is called during every change detection
template: '<p>{{ message }}</p>',
cycle. })
export class AppComponent implements DoCheck {
message: string = 'No changes detected';
The ngDoCheck lifecycle hook in Angular
provides a way to detect and respond to ngDoCheck() {
changes that Angular doesn't catch this.message = 'Change detected!';
automatically. This hook is called }
during every change detection cycle, }
giving you the ability to perform custom
change detection and respond to changes
that might not be detected by Angular's
default change detection mechanism
ngAfterContentInit and ngAfterContentChecked:
ngAfterContentInit is called after the import { Component, AfterContentInit, AfterContentChecked } from
component's content has been initialized. '@angular/core';
@Component({
ngAfterContentChecked is called after every selector: 'app-root',
check of the component's content. template: '<ng-content></ng-content><p>{{ message }}</p>',
})
export class AppComponent implements AfterContentInit,
AfterContentChecked {
message: string = '';
ngAfterContentInit() {
console.log('Content initialized!')
this.message = 'Content initialized!';
}
ngAfterContentChecked() {
console.log('Content checked!')
this.message = 'Content checked!';
}
}
ngOnDestroy
This hook is called just before the import { Component, OnDestroy } from '@angular/core';
component is destroyed.
@Component({
selector: 'app-root',
template: '<p>{{ message }}</p>',
})
export class AppComponent implements OnDestroy {
message: string = '';

ngOnDestroy() {
this.message = 'Component destroyed!';
}
}
Routing Angular is writing is technique to redirect to
appropriate page. Multiple components comprises of a
single angular application.
Routing in Angular allows you to
navigate between different Clicking links, entering direct url in address bar,
components and views in a single- or using history pages are the routing
page application (SPA) without
reloading the entire page. implementations.

Angular's Router provides a


powerful and flexible way to handle
So, Routing is the process of partitioning
navigation application's UI using URLs.

It enables programmers to create modern single-page-


import { RouterModule, Routes }
apps with numerous views that may be loaded once by
from '@angular/router';
a browser.
Routing Process
import { NgModule } from '@angular/core';

Routing import { BrowserModule } from '@angular/platform-browser';


import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';

ng new routing import { HomeComponent } from './home/home.component';


import { AboutComponent } from './about/about.component';
cd routing import { ContactComponent } from './contact/contact.component';
const routes: Routes = [
ng generate component home
{ path: '', component: HomeComponent },
ng generate component about { path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
ng generate component contact
];
@NgModule({
In your app.module.ts, import declarations: [AppComponent,HomeComponent,AboutComponent,ContactComponent,],
RouterModule and configure imports: [
your routes. [RouterModule.forRoot(routes)], BrowserModule],
exports: [RouterModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In your app.component.html, add the In your app.component.ts, add the
<router-outlet></router-outlet> where following:
the routed components will be
displayed:

import { Component } from


<div>
'@angular/core';
<h1>My Angular App</h1>
<nav>
@Component({
<a routerLink="/">Home</a>
selector: 'app-root',
<a routerLink="/about">About</a>
templateUrl: './app.component.html',
<a
styleUrls: ['./app.component.css']
routerLink="/contact">Contact</a>
})
</nav>
export class AppComponent {
<router-outlet></router-outlet>
</div>
}
You can now navigate between different components And in your component, access the parameter using
using the links you've created: ActivatedRoute:

● Clicking on "Home" will load the import { ActivatedRoute } from


HomeComponent. '@angular/router';
● Clicking on "About" will load the
AboutComponent. constructor(private route:
● ActivatedRoute) {
Clicking on "Contact" will load the
this.route.params.subscribe(params
ContactComponent.
=> {
this.userId = params['id'];
});
}
Route Parameters:
To handle route parameters, you can modify your
routes like this:

const routes: Routes = [


{ path: 'user/:id', component: UserProfileComponent },
];
Route parameters, lazy loading, and additional route configurations provide flexibility in building complex single-page
applications

Lazy Loading:

Lazy loading is a powerful feature for improving the performance of your Angular applications by loading only the necessary
modules when they are required.

It's particularly beneficial in large applications where loading everything upfront can lead to slower initial load times. User

const routes: Routes = [


{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) },
];
PIPES DecimalPipe: Formats a number as a decimal
number.
{{ floatValue | number:'1.2-2' }}
UpperCasePipe / LowerCasePipe: Converts a
string to uppercase or lowercase.
SlicePipe: Extracts a portion of a string or
{{ textValue | uppercase }} an array.

{{ textValue | lowercase }} {{ stringValue | slice:1:5 }}


{{ arrayValue | slice:1:3 }}

CurrencyPipe: Formats a number as Create a project:


currency using the given currency code ng new pipes-example
and other options. cd pipes-example

{{ priceValue |
currency:'USD':'symbol':'1.2-2' }}
<!-- app.component.html -->

<h2>Date Pipe:</h2>
// app.component.ts
<p>Current Date: {{ currentDate |
date:'dd/MM/yyyy' }}</p>
import { Component } from '@angular/core';
<h2>UpperCase and LowerCase Pipes:</h2>

<p>Original Text: {{ textValue }}</p> @Component({

<p>Uppercase: {{ textValue | uppercase }}</p> selector: 'app-root',


templateUrl: './app.component.html',
<p>Lowercase: {{ textValue | lowercase }}</p>
styleUrls: ['./app.component.css']
<h2>Currency Pipe:</h2>
})
<p>Price: {{ priceValue | currency:'USD':'symbol':'1.2- export class AppComponent {
2' }}</p>
currentDate: Date = new Date();
<h2>Decimal Pipe:</h2>
textValue: string = 'Hello Angular';
<p>Float Value: {{ floatValue | number:'1.2-2' }}</p> priceValue: number = 1234.5678;

<h2>Slice Pipe:</h2> floatValue: number = 3.14159;


stringValue: string = 'Angular';
<p>Sliced String: {{ stringValue | slice:1:5 }}</p>
arrayValue: number[] = [10, 20, 30, 40, 50];
<p>Sliced Array: {{ arrayValue | slice:1:3 | json
}
}}</p>
ng g c student-list
Routing ng g c teacher-list
Angular generate component student-list
ng new angular-routing-
demo --routing
Configure routes by navigating to app.routing.module.ts.
All the routes used in the apps are called here, each route is

--routing considered as an object.


Update routes:
Flag indicates that this project will be
const routes: Routes = [
created with routing enabled
{path: 'students', component:StudentListComponent},
{path: 'teachers', component:TeacherListComponent},
See in app.module.ts file, routing is already
];
there.

Export the modules in the last line to avoiding duplication in


app.module.ts:

export const routingComponents = [StudentListComponent,


TeacherListComponent]
Routing import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

Updates in app.module.ts: import { AppRoutingModule, routingComponents } from './app-routing.module';


import { AppComponent } from './app.component';
import { AppRoutingModule,
routingComponents } from @NgModule({

'./app-routing.module'; declarations: [
AppComponent,
routingComponents
Import the routing
],
components and update it in
imports: [
declarations. Now we donot BrowserModule,
need additional components AppRoutingModule
to add up in here, just ],
update the routing file with providers: [],

the components and export bootstrap: [AppComponent]

them })
export class AppModule { }
Routing Navigate to:
http://localhost:4200/students
http://localhost:4200/teachers
Open app.component.html file:
In app.component.html create anchor tags:
<router-outlet></router-outlet>
<nav>
This component directive is already
<a routerLink="/students">
there.
<button>STUDENTS</button>
</a>
<div style="text-align: center;">
<a routerLink="/teachers">
<h1>
<button>TEACHERS</button>
This is routing page
</a>
</h1>
</nav>
</div>

Now buttons are on the page.


<router-outlet></router-outlet>
PIPES Angular provides several built-in pipes, and
you can also create custom pipes to suit your
specific requirements.
Pipes are a feature that allows you to
transform data before displaying it in
the template. To use a pipe in Angular, you apply it to a
value within the template using the | (pipe)
They are used to format and manipulate
operator, followed by the pipe name and any
the data in a concise and reusable way.
additional parameters required for that
Pipes can be applied to expressions in specific pipe.
the template to perform tasks such as
formatting dates, converting text to
DatePipe: Formats a date value according to
uppercase or lowercase, filtering lists,
and more the given format.
{{ currentDate | date:'dd/MM/yyyy' }}
Hooks Deep Dive During the process (create instance to
destroy) there are several stages that angular

Angular application does not use all the covers and this is called as component life
components at once. It only uses the one cycle or angular hooks.
or more which are required.

Whenever angular needs to use a So these stages are represented by some


component, it creates a new instance of methods or hooks as:
that component and start using it in DOM.
ngOnChanges, ngOnInIt, ngDoCheck,
So if the new page is redirected the ngAfterContentInIt, ngAfterContentChecked,
components needed will be added as an
ngAfterViewInit, ngAfterViewChecked,
instance
ngOnDestroy.
One the use is done angular destroy this
instance and remove from DOM.
All the above hooks or methods have and
interface that we need to implement
separately.
Hooks Deep Dive Constructor
Every component has its own constructor that
To find the corresponding interface just is executed before lifecycle hooks
remove the ng text from method. So dependencies that are required for
Example: lifecycle hooks can be injected in here.

Method Name: ngOnInIt


ng g s message
Interface Name: OnInIt S : Service is a reusable, singleton object
that encapsulates specific functionality and
data and can be shared across components.
Every component maybe a parent or a child
have its own lifecycle hooks. Services are a fundamental building block of
an Angular application, and they are used to
So methods will be executed in 8
different sequence. centralize and organize code that can be
shared among different parts of an
application.
Hooks Deep Dive NgOnChange:
1st stage of lifecycle
Open the newly created service Is called whenever our one of our bound Input
changes
Create a method:
Changes occur on those properties which are
getMessage(): String { decorated with @Input method
return "THIS IS MESSAGE SERVICE"
}

Go to the app.component.ts @Input


Whenever we communicate between parent and child
Create a constructor just like a component, then the passing prop from parent
function.
component is always received by child with @Input
msg: String; decorator. When the values change, then this hook is
constructor (private msgService: invoked in the child component and we can get the
MessageService) {
details about which input properties have changed
this.msg = msgService.getMessage()
console.log(this.msg)
}
// CHILD, include FormsModule in app.module
NgOnChange

import { Component, Input, OnChanges, SimpleChanges } from


Create two components: '@angular/core';

Ng g module child
@Component({
Ng g c parent selector: 'app-child',
import { Component } from '@angular/core'; template: '<p>{{ childMessage }}</p>',
})
@Component({ export class ChildComponent implements OnChanges {
selector: 'app-parent', @Input() messageFromParent: string = '';
template: `
<input [(ngModel)]="parentMessage" childMessage: string = '';
placeholder="Enter message" />
<app-child ngOnChanges(changes: SimpleChanges): void {
[messageFromParent]="parentMessage"></app-child> if (changes['messageFromParent']) {
`, this.childMessage = `Child received: $
}) {changes['messageFromParent'].currentValue}`;
export class ParentComponent { }
parentMessage: string = ''; }
} }
Update the consoles on every step.
NgOnChange
Visualize that whenever the field is updated only
In this example, the ParentComponent has the child ngOnChange is called not event the parent
ngonChange neither any of the constructors.
an input property parentMessage, and the
ChildComponent has an input property Add two strings in child :
messageFromParent. currValue: string = '';
prevValue: string = '';

The ngOnChange hook in the ChildComponent Add the following loop into the ngOnChange and
console
is used to detect changes in the
messageFromParent property and update the for (let propertyName in changes) {
let change = changes[propertyName]
childMessage accordingly.
this.currValue = change.currentValue
this.prevValue = change.previousValue
ngOnChange lifecycle hook is used to console.log(propertyName + " : curr val" + this.currValue + " :
prev val" + this.prevValue )
detect changes to the input properties of
}
a component
So current and previous values are available in it by default

You might also like