Angular
Angular
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
ng serve Write the basic code with two public available variables and import it into
the app.component.ts.
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:
*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">
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
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
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
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
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
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>
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>
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
component is initialized.
@Component({
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.
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
{{ 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>
'./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: [],
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>
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.
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