0% found this document useful (0 votes)
20 views63 pages

Angular Programs

Uploaded by

ap s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views63 pages

Angular Programs

Uploaded by

ap s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

program-1:Use bootstrap

-----------------------
1. npm install bootstrap
2. add the below line in '[Link]'
@import 'bootstrap/dist/css/[Link]';
3. add "node_modules/bootstrap/dist/js/[Link]" in [Link]
projects ->architect->build->scripts:[]

program-2:display Local image


-----------------------------
1. place the images inside 'public' folder (project1/public/images)
2. use it in HTML file
<img src='images/[Link]' />

program-3:interpolation and property binding


----------------------------------------
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<div>
<h1 [innerHtml]='myText'></h1>
<img [src]='imagePath'/>
<img bind-src ='imagePath'/>
<h2 [innerHtml]='2+3'></h2>
<hr>
<h1>{{myText}}</h1>
<img src='{{imagePath}}'/>
<h2>{{2+3}}</h2>
</div>`
})
export class AppComponent {
myText: string = 'Interpolation';
imagePath: string = '[Link]
nav@[Link]';
}

program-4:interpolation vs property binding


-------------------------------------------
->to set an element property to a non-string data value, property binding should be
used and not interpolation binding

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


@Component({
selector: 'my-app',
template: `<div>
<button disabled='{{isDisabled}}'>Try Me</button>
<br/><br/>
<button [disabled]='isDisabled'>Try Me</button>
<br/><br/>
<button bind-disabled='isDisabled'>Try Me</button>
</div>`
})
export class AppComponent {
isDisabled: boolean = false;
}

program-5:interpolation vs property binding


-------------------------------------------
->for String Concatination, interpolation binding should be used insteadof property
binding

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


@Component({
selector: 'my-app',
template: `<div>
<h1>My Name is {{myText}}</h1>
<img src='[Link]

<h1> a is {{a}} b is {{b}} addition is {{a+b}}</h1>

<h1>{{ 'a is '+a+' b is '+b+' additon is '+(a+b) }}</h1>


</div>`
})
export class AppComponent {
name: string = 'Sachin Tendulkar';
imagePath: string = 'assets/images/logos/angular/logo-nav@[Link]';
}

program-6:Event binding
-----------------------
@Component({
selector: 'my-app',
template: `<div>
<h1>click the below button to invoke the function</h1>
<button (click)="f1()">btn-1</button>
<br/><hr/>
<h1 [hidden]='flag'>Show/Hide this Paragraph By Clicking the
Below Button</h1>
<button (click)="flag = !flag" >btn-2</button>
</div>`
})
export class AppComponent {
flag:boolean = false;
f1(){
alert("I am f1")
}
}

program-7:Property-Binding vs Attribute-Binding
===============================================
-Attributes exist in the HTML markup. Attribute values are static and are not
updated dynamically
-Properties exist on the DOM nodes in real-time. Any changes to myName in the
component will be reflected in the input.

<input type="text" [value]="myName" />


<input type="text" [[Link]]="myName" />
<button class="btn btn-primary" (click)="myName='Rahul'">Change Name</button>
Program-8:Dark/Light Mode
=========================
toggleMode() {
[Link] = ![Link];
if ([Link]) {
[Link]('dark');
} else {
[Link]('dark');
}
}

program-9:Template Reference Variable


=====================================
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<div>
number1:
<input #num1 /> <br/><br/>
number2:
<input ref-num2 /> <br/><br/>

<button (click)="add([Link],[Link])">Add</button>
</div>`
})
export class AppComponent {
add(a,b){
alert(Number(a)+Number(b));
}
}

program-10 : Two-way data binding


===============================
import { FormsModule } from '@angular/forms';
imports: [FormsModule]

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


@Component({
selector: 'my-app',
template : `<div>
<input [(ngModel)]="name" />
<input bindon-ngModel='name' />
Your Name is: {{name}}
</div>`
})
export class AppComponent {
}
Program-11: View Encapsulation
-----------------------------
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>MyProject1</title>
<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">


<link rel="icon" type="image/x-icon" href="[Link]">
<style>
.hello {
font-size: 40px;
border: 5px solid red;

}
</style>
</head>
<body>
<my-root>Loading...</my-root>
<p class="hello">This is a paragraph from [Link] file</p>
</body>
</html>
*********************
import { Component, ViewChild, ViewEncapsulation } from '@angular/core';

@Component({
selector: 'my-root',
template: "<div class='hello'>Hello World</div>",
encapsulation: [Link],
//encapsulation: [Link]/Native/Emulated(Default),
styles: ['.hello{background-color:green;']
})
export class AppComponent {

program-12:Template Reference Variable @viewChild


==================================================
import { Component, ViewChild } from '@angular/core';

@Component({
selector: 'my-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
@ViewChild('name') nameRef;
@ViewChild('age') ageRef;

myName;
myAge;
showData() {
[Link] = [Link];
[Link] = [Link];
alert(`${[Link]} ${[Link]}`)
}
}
*******************
<h1>Using Template Reference variable in component file</h1>
Name: <input #name><br><br>
Age: <input ref-age><br><br>
<button (click)='showData()'>get Date</button>

program-13: Conditional Display Using @if()


===========================================
@if(num%2 == 0){
<h4>{{num}} is Even </h4>
}@else{
<h4>{{num}} is Odd </h4>
}

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

@Component({
selector: 'app-root',
template: `
<ng-template
*ngIf="x%2==0;then evenBlock; else oddBlock">
</ng-template>

<ng-template #evenBlock>
<p>
{{x}} is an even number
</p>
</ng-template>

<ng-template #oddBlock>
<p>
{{x}} is an odd number
</p>
</ng-template>
`
})
export class AppComponent {
x: number = 9;
}

program-14: ngswitch directive


==================================
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
@switch (num) {
@case (1) { <h1>Monday</h1> }
@case (2) { <h1>Tuesday</h1> }
@case (3) { <h1>Wednesday</h1> }
@case (4) { <h1>Thursday</h1> }
@case (5) { <h1>Friday</h1> }
@case (6) { <h1>Saturday</h1> }
@case (7) { <h1>Sunday</h1> }
@default { <h1>Not a Valid number</h1>> }
}
`
})
export class AppComponent {
x: number = 2;
}

program-15:class binding
==============================
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
styles:['.myClass{color:red;border:5px solid green;}'],
template: `
<h1>
<p [[Link]]='flag'> Add a class to an element </p>
<p [ngClass]="myClasses"> Add Multiple classes to an element </p>
<p [ngClass]="myFunction()"> Add Multiple classes to an element </p>
<button class="btn" [ngClass]="flag ? 'btn-success' : 'btn-danger'">
Class Binding example
</button>
</h1>`
})
export class AppComponent {
flag : boolean = true;
myClasses = {
class1 : true,
class2 : false,
class3 : true
}
myFunction(){
return [Link];
}
}

program-16:style binding
========================
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `
<h1>
<p [[Link]]="num % 2 == 0 ? 'blue' : 'red'"> Add a style </p>
<p [[Link]]='48'> Add style with unit </p>
<p [[Link]-color]=" flag?'green':'blue' "> Add style conditionally
</p>
<p [ngStyle]="myStyles"> NgStyle for multiple values </p>
<p [ngStyle]="myFunction()"> NgStyle for multiple values </p>
</h1>`
})
export class AppComponent {
flag : boolean = true;
myStyles = {
'background-color': 'lime',
'font-size': '20px',
'border': '5px dotted red',
'padding':'20px'
}
myFunction(){
return [Link];
}
}

<div>States datalist</div>
<input list="states" name="state" id="state" [(ngModel)]="selectedState">
<datalist id="states">
@for(state of statesArr;track $index){
<option>{{state}}</option>
}
</datalist>
<div>Selected state: {{selectedState}}</div>

program-17: ngFor directive with trackBy


=========================================
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '[Link]'
})
export class AppComponent {
employees = [
{ "eId": 101, "name": "sanjay", "sal": 5000, "gender": "male" },
{ "eId": 104, "name": "geeta", "sal": 8000, "gender": "female" },
{ "eId": 103, "name": "sameer", "sal": 7000, "gender": "male" },
{ "eId": 102, "name": "sita", "sal": 9000, "gender": "female" },
{ "eId": 105, "name": "deepak", "sal": 8000, "gender": "male" }
];
updateEmployeeData() {
[Link] = [
{ "eId": 101, "name": "sanjay", "sal": 5000, "gender": "male" },
{ "eId": 104, "name": "geeta", "sal": 8000, "gender": "female" },
{ "eId": 103, "name": "sameer", "sal": 7000, "gender": "male" },
{ "eId": 102, "name": "sita", "sal": 9000, "gender": "female" },
{ "eId": 105, "name": "deepak", "sal": 8500, "gender": "male" }
];
}
}
************************
<div class="row">
<table class="table table-bordered table-striped">
<tbody>
@for(employee of employees;track [Link]){
<tr>
<td>{{$index+1}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{$first}}</td>
<td>{{$last}}</td>
<td>{{$even}}</td>
<td>{{$odd}}</td>
</tr>
}
</tbody>
</table>
</div>
<button class="btn btn-primary" (click)="updateEmployeeData()">Click Me</button>

Program-18 : Pagination
==========================
1. Install Pagination Library using the below command
npm i ngx-pagination
2. Add pagination module
import { NgxPaginationModule } from 'ngx-pagination';
imports: [ BrowserModule, NgxPaginationModule]
3. in HTML file add the below line
@for(user of users | paginate: { itemsPerPage: 4, currentPage: p };track
$index)
<pagination-controls (pageChange)="p = $event"></pagination-controls>

Program-19 : star Rating


========================
rating: number = 3;
maxStars: number = 5;
stars: boolean[] = [];
ngOnInit() {
[Link] = Array([Link]).fill(false);
}
rate(stars: number) {
[Link] = stars;
}
--------------------------------
<div class="star-rating">
@for( star of stars; let i = $index;track $index){
<span (click)="rate(i + 1)" class="star" [[Link]]="i < rating">

</span>
}
</div>
--------------------------
.star {
font-size: 2rem;
cursor: pointer;
color: grey;
}
.[Link] {
color: gold;
}

Program-20 : Custom Directive


=============================
import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
selector: '[numberonly]'
})
export class NumberonlyDirective {
@HostBinding('[Link]-color')
myBgColor: string = '';

@HostListener('keyup', ['$[Link]'])
handleKeyUp(value: string) {
let regex = new RegExp(/^[0-9]*$/);
if (![Link](value)) {
[Link] = 'red';
} else {
[Link] = 'cyan';
}
}
}

******************
<input type="text" numberonly name="salary" id="salary">

Program-21: Custom Directive - Highlight


===========================================
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private ele: ElementRef) {
[Link](ele);
}
@HostListener('mouseenter') onMouseEnter() {
[Link]('yellow', 'red');
}
@HostListener('mouseleave') onMouseLeave() {
[Link]('', '');
}
private highlight(bgColor: string, color: string) {
[Link] = bgColor;
[Link] = color;
}
}
---------------------------------
<span appHighlight>this is a paragraph</span>
Program-22: Custom Directive - Zoomin
======================================
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[zoomin]'
})
export class ZoominDirective {
constructor(private ele: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
[Link] = 'scale(100%,120%)'
}
@HostListener('mouseleave') onMouseLeave() {
[Link] = 'scale(100%)'
}
}

Program-23: Custom Directive - Back Button


===========================================
import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common'

@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {

constructor(private location: Location) { }

@HostListener('click')
clickHandler(e) {
[Link]();
}
}

Program-24 : Tooltip Directive


===============================
import { Directive, ElementRef, HostListener, Input, Renderer2 } from
'@angular/core';
@Directive({
selector: '[appTooltip]'
})
export class TooltipDirective {
@Input()
tooltipText!: string;
tooltipElement!: HTMLElement;

constructor(private el: ElementRef, private renderer: Renderer2) {}


@HostListener('mouseenter') onMouseEnter() {
[Link] = [Link]('span');
const text = [Link]([Link]);
[Link]([Link], text);
[Link]([Link], [Link]);
[Link]([Link], 'tooltip');
}

@HostListener('mouseleave') onMouseLeave() {
[Link]([Link], [Link]);
}
}

<button appTooltip="Save your changes">Save</button>

Program-25 : How to use Modal


=============================
1. npm i bootstrap
2. Add the below TS code
selectedEmployee:any;
displayStyle = 'none';
openPopup(emp:any) {
[Link] = emp;
[Link] = 'block';
}
closePopup() {
[Link] = 'none';
}
2. Add the below modal code

<button class="btn btn-secondary" (click)="openPopup(emp)">View</button>

<div class="modal" tabindex="-1" role="dialog" [ngStyle]="{ display:


displayStyle }">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body">
<p>id: {{ selectedEmployee?.eId }}</p>
<p>Name: {{ selectedEmployee?.name }}</p>
<p>sal: {{ selectedEmployee?.sal }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger"
(click)="closePopup()">
Close
</button>
</div>
</div>
</div>
</div>
program-26 : async pipe
========================
import { Component } from "@angular/core";
import { Observable,interval } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: '[Link]'
})
export class AppComponent {
createObservable3 = interval(2000);
testObservable3 = [Link](val => [Link](val));
}
**********
<h1>Observable Example</h1>
<h1>{{createObservable3 | async }}</h1>

program-27 : Custom Pipe(Remaining Char)


========================================
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'count'
})
export class CountPipe implements PipeTransform {
transform(input){
var output = 150 - [Link];
return output;
}
}

program-28 : Custom Pipe(Age Pipe)


==================================
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'age',
})
export class AgePipe implements PipeTransform {
transform(value: Date): any {
if(!value) return '';
const currentYear = new Date().getFullYear();
const dobYear = new Date(value).getFullYear();
const age = currentYear - dobYear;
return age + ' years old';
}
}
program-29: Custom Pipe(Truncate)
=================================
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 20, completeWords = false, ellipsis = '...') {
if (completeWords) {
limit = [Link](0, limit).lastIndexOf(' ');
}
return [Link] > limit ? [Link](0, limit) + ellipsis : value;
}
}
<h1>{{longStr | truncate }}</h1>
<!-- Outputs: A really long string that... -->

<h1>{{longStr | truncate : 12 }}</h1>


<!-- Outputs: A really lon... -->

<h1>{{longStr | truncate : 12 : true }}</h1>


<!-- Outputs: A really... -->

<h1>{{longStr | truncate : 12 : false : '***' }}</h1>


<!-- Outputs: A really lon*** -->

program-30: Custom Pipe(Search)


=================================
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;

searchText = [Link]();
return [Link](item => {
return [Link](item).toLowerCase().includes(searchText);
});
}
}

program-31: Custom Pipe(Mr. Miss)


=================================
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'title'
})
export class SearchPipe implements PipeTransform {
transform(name:any, emp?:any): any {
if([Link] == 'male')
return "mr. "+name
else
return "miss. "+name
}
}

program-32: use pre-defined pipes in component


===============================================
import { Component, ViewChild } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

@Component({
selector: 'my-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
providers: [CurrencyPipe]
})
export class AppComponent {
constructor(private currencyPipe: CurrencyPipe) {

}
sal = 5000;
formattedSal1 = [Link]([Link]);
formattedSal2 = [Link]([Link], '$');
}

program-33: pure pipe vs impure pipe


====================================
-A pure pipe is only called when Angular detects a change in the value
or the parameters passed to a pipe.(on component load only)

-An impure pipe is called for every change detection cycle


no matter whether the value or parameters changes.(on every change)

-By Default every pipe is pure pipe

ex:
@Pipe({
name: 'myCustomPipe',
pure: true/false
})

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


@Component({
selector: 'app-root',
template: `
<h2>
enter a number
<input [(ngModel)]="x" #num /> &nbsp;
<button (click)="addNewDigit([Link])">add</button><hr>

Original array:
<span *ngFor="let digit of originalList">
<b>{{digit}}</b>, &nbsp;
</span><hr>

Pure Pipe: <br>List is being sorted on component load only<br>


<span *ngFor="let digit of pureSortableDigits | pureSort">
<b>{{digit}}</b>, &nbsp;
</span><hr>

ImPure Pipe:<br>List is being sorted on every change<br>


<span *ngFor="let digit of impureSortableDigits | impureSort">
<b>{{digit}}</b>, &nbsp;
</span>
</h2>
`
})
export class AppComponent {
newDigit: number

originalList: number[] = [
2, 3, 4, 1
]

pureSortableDigits: number[] = [
2, 3, 4, 1
]

impureSortableDigits: number[] = [
2, 3, 4, 1
]

addNewDigit(newDigit) {
[Link](newDigit)
[Link](newDigit)
[Link](newDigit)
}
}

program-34 : inputs and outputs(component communication)


========================================================
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<h3>Parent Component <br>
x from its own component is: {{x}} <br>
y from its own component is: {{y}} <br>

a from child is: {{aParent}} <br>


b from child is: {{bParent}} <br>

<hr>
<app-child [xChild]='x' [yChild]='y'
(aEvent)="getA($event)" (bEvent)="getB($event)"></app-child>
</h3>`
})
export class ParentComponent {
x: number = 10;
y: number = 20;
aParent : number;
bParent : string;

getA(temp:number){
[Link] = temp;
}
getB(temp:string){
[Link] = temp;
}
}
****
import { Component, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
inputs: ['xChild', 'yChild'],
outputs: ['aEvent', 'bEvent'],
template: `<h3>Child Component</h3>
a from its own component is: {{a}} <br>
b from its own component is: {{b}} <br>

x value from parent is: {{xChild}} <br>


y value from parent is: {{yChild}} <br>

<button (click)='sendA()'>send a data</button>&nbsp;


<button (click)='sendB()'>send b data</button>
`
})
export class ChildComponent {
xChild: number;
yChild: number;

a: number = 15;
b: string = "hiiiiii";

aEvent = new EventEmitter<number>();


bEvent = new EventEmitter<string>();

sendA():void{
[Link](this.a);
}
sendB():void{
[Link](this.b);
}
}

program-35 : Flipkart Categories


=================================
allCategories = [
{ label: 'Grocery', img_url:
'[Link] },
{ label: 'Mobile', img_url:
'[Link] },
{ label: 'Fashion', img_url:
'[Link]
q=100' },
{ label: 'Electronics', img_url:
'[Link] },
{ label: 'Home & Furniture', img_url:
'[Link] },
{ label: 'Appliances', img_url:
'[Link]
q=100' },
{ label: 'Travel', img_url:
'[Link] },
{ label: 'Beauty & Toys', img_url:
'[Link] },
{ label: 'Two Wheeler', img_url:
'[Link]
q=100' },
]

<div class="container">
<div class="row">
@for(categoryObj of allCategories;track $index){
<div class="col">
<app-category [categoryObj]="categoryObj"></app-category>
</div>
}
</div>
</div>

<div class="category text-center">


<img src={{categoryObj.img_url}} alt="">
<div>{{[Link]}}</div>
</div>

.category img{
width:65px;
height:65px;
}
.category div{
font-size: 12px;
font-weight: 700;
}

program-36 : life cycle hooks all methods


==========================================
import { Component } from "@angular/core";
@Component({
selector: 'app-root',
templateUrl: '[Link]',
styleUrls: ['[Link]']
})
export class AppComponent {
num = 0;

constructor() {
[Link]("Parent constructor")
}
ngOnInit() {
[Link]('Parent ngOnInit');
}
ngOnChanges() {
[Link]('Parent ngOnChanges');
}
ngDoCheck() {
[Link]('Parent ngDoCheck');
}
ngAfterContentInit() {
[Link]('Parent ngAfterContentInit');
}
ngAfterContentChecked() {
[Link]('Parent ngAfterContentChecked')
}
ngAfterViewInit() {
[Link]('Parent ngAfterViewInit');
}
ngAfterViewChecked() {
[Link]('Parent ngAfterViewChecked');
}
ngOnDestroy() {
[Link]('Parent ngOnDestory');
}
increment() {
[Link]++;
}
}
------
<h1>
this is app component <br>
Parent Component num: {{num}} <br>
<button (click)="increment()">Increment(+)</button> <br>
<hr>
<app-my-child [childNum]='num'></app-my-child>
</h1>
---------
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'my-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
inputs: ['childNum']
})
export class MychildComponent implements OnInit {
constructor() {
[Link]('child constructor');
}
ngOnInit() {
[Link]('child ngOnInit');
}
ngOnChanges() {
[Link]('child ngOnChanges');
}
ngDoCheck() {
[Link]('child ngDoCheck');
}
ngAfterContentInit() {
[Link]('child ngAfterContentInit');
}
ngAfterContentChecked() {
[Link]('child ngAfterContentChecked')
}
ngAfterViewInit() {
[Link]('child ngAfterViewInit');
}
ngAfterViewChecked() {
[Link]('child ngAfterViewChecked');
}
ngOnDestroy() {
[Link]('child ngOnDestory');
}

}
--------
<p>
This is child component <br>
child component Num: {{childNum}}
</p>

program-37 : ngDOCheck()
============================
import { Component, OnInit, OnChanges, ChangeDetectionStrategy, DoCheck,
ChangeDetectorRef } from '@angular/core';

@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
inputs: ['xChild'],
changeDetection: [Link]
})
export class ChildComponent implements OnChanges, OnInit, DoCheck {
constructor(private changeDetectorObj: ChangeDetectorRef) {
}
ngOnChanges(myChanges) {
[Link]('onchanges called', myChanges)
}
ngOnInit() {
[Link]('oninit called')
}
ngDoCheck() {
[Link]();
}
}

program-38 - ngDoCheck
======================
import { Component, DoCheck, KeyValueDiffers, KeyValueDiffer } from
'@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
})
export class AppComponent implements DoCheck {
user = { name: 'John Doe' };
private userDiffer: KeyValueDiffer<string, any>;
changes: string[] = [];
changeUserData(newName: string) {
[Link] = newName;
}
constructor(private keyValueDiffers: KeyValueDiffers) {
[Link] = [Link]([Link]).create();
}
ngDoCheck() {
const userChanges = [Link]([Link]);
if (userChanges) {
[Link](item => {
[Link](`Property ${[Link]} changed from ${[Link]}
to ${[Link]}`);
});
}
}

-------------------
<div>
<h2>Change Object Property</h2>
<input [(ngModel)]="[Link]" placeholder="Enter user name">
<button (click)="changeUserData()">Change User Name Programmatically</button>
</div>
<div>
<h3>Current User Details:</h3>
<p>Name: {{ [Link] }}</p>
</div>
<div>
<h3>Changes Detected:</h3>
<p *ngFor="let change of changes">{{ change }}</p>
</div>

program-39 : @ViewChild and ngAfterViewInit lifecycle hooks


===========================================================
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent implements AfterViewInit {
@ViewChild('myInputBox') inputBox;

constructor() {
[Link]([Link]); //not yet available
}
ngAfterViewInit() {
[Link]();
[Link]([Link])
}
}
*************
<h1>@ViewChild to inject a reference to a DOM element</h1>
<input type="text" #myInputBox>
Program-40 : @viewChild to access child members in parent component
===================================================================
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/[Link]'

@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) childRef;

constructor() {
[Link]("inside constructor")
// [Link]([Link].a); //not yet available
// [Link]([Link].b); //not yet available
}
ngAfterViewInit() {
[Link]("inside ngAfterViewInit")
[Link]([Link].a);
[Link]([Link].b);
}

Program-41 : @viewChildren
===============================
@ViewChildren('myInputBox') allinputBoxes: any;

ngAfterViewInit() {
[Link]([Link]);
[Link]._results?.forEach((ele: any) => {
[Link] = 'green';
});
}

Program-42 : renderer
==========================
import { Component, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `<div #myDiv>Content here</div>`,
})
export class ExampleComponent implements AfterViewInit {
constructor(private renderer: Renderer2, private el: ElementRef) {}
ngAfterViewInit(): void {
const div = [Link]('div');

// Add a CSS class


[Link](div, 'highlight');

// Set a style property


[Link](div, 'color', 'blue');

// Add an attribute
[Link](div, 'role', 'button');

// Listen to an event
[Link](div, 'click', () => {
[Link]('Div clicked!');
});
}
}

Program-43 : [Link]()
=============================================
<!-- [Link] -->
<div>
<h1>Dynamic Component Example</h1>
<button (click)="loadDynamicComponent()">Load Dynamic Component</button>
<ng-container #dynamicContainer></ng-container>
</div>

// [Link]
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './[Link]';

@Component({
selector: 'app-root',
templateUrl: './[Link]',
})
export class AppComponent {
@ViewChild('dynamicContainer', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;

loadDynamicComponent() {
// Clear any previously inserted components
[Link]();

// Dynamically create and insert the component


[Link](DynamicComponent);
}
}

program-44: create a math Services


======================================
import { Injectable } from '@angular/core';
@Injectable()
export class MathService {
add(a:number,b:number){
return a+b;
}
sub(a:number,b:number){
return a-b;
}
mul(a:number,b:number){
return a*b;
}
div(a:number,b:number){
return a/b;
}
}
*********
import { Component } from "@angular/core";
import { MathService } from './[Link]'

@Component({
selector: 'app-root',
templateUrl: '[Link]',
styleUrls: ['[Link]']
})
export class AppComponent {
addResult;
subResult;
mulResult;
divResult;

constructor(obj : MathService){
let a = parseInt(prompt("enter a value"));
let b = parseInt(prompt("enter a value"));
[Link] = [Link](a,b);
[Link] = [Link](a,b);
[Link] = [Link](a,b);`
[Link] = [Link](a,b);
}
}

program-45: httpClient example


================================
import { Component } from "@angular/core";
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-root',
templateUrl: '[Link]',
styleUrls: ['[Link]']
})
export class AppComponent {
result;
constructor(obj: HttpClient) {
[Link]('[Link]
.subscribe((response) => {
[Link](response);
[Link] = response;
});
}
}

program-46 : HttpClient with Headers


=======================================
Reading the full response(not only the body)

[Link]('[Link]
{ observe: 'response' }).subscribe(
(res)=>{
[Link](res)
}
)

program-47: httpClientt (Todo Service)


======================================
[Link]
-------
export interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
[Link]
---------------
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Todo } from './todo'
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class TodoService {
constructor(public httpObj: HttpClient) {
}
getAllTodos(): Observable<Todo[]> {
return [Link]<Todo[]>('[Link]
}
}
[Link]
-----------------
import { Component } from "@angular/core";
import { Todo } from './todo';
import { TodoService } from './[Link]'

@Component({
selector: 'app-root',
templateUrl: '[Link]',
styleUrls: ['[Link]']
})
export class AppComponent {
todos: Todo[];
constructor(public todoServiceObj: TodoService) {
}
ngOnInit() {
[Link]()
.subscribe((response: Todo[]) => {
[Link] = response;
});
}
}

program-48 : Http with Model & Observable


==========================================
export class Comment {
constructor(
public id: number,
public postId: number,
public name: string,
public email: string,
public body: string
) {}
}
*********
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Comment } from './comment';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class CommentService {
private url = '[Link]
constructor(private http: HttpClient) {
}
getAllComments(): Observable<Comment[]> {
return [Link]<Comment[]>([Link], { observe: "body" }).pipe(
map((res: Comment[]) => {
return [Link]((item: Comment) => {
return new Comment([Link],[Link],[Link],[Link],[Link]);
});
})
);
}
}
*************
import { Component } from "@angular/core";
import { Comment } from './comment';
import { CommentService } from './[Link]'

@Component({
selector: 'app-root',
templateUrl: '[Link]'
})
export class AppComponent {
commentList: Comment[];

constructor(public ob: CommentService) {


[Link]().subscribe((response: Comment[]) => {
[Link] = response;
[Link]([Link]);
});
}
}

Program-49 : Model Class


==========================
export class Employee {
id: number;
firstName: string;
lastName: string;
sal: number;

constructor(id: number, firstName: string, lastName: string, sal: number) {


[Link] = id;
[Link] = firstName;
[Link] = lastName;
[Link] = sal;
}
getFullName(): string {
return `${[Link]} ${[Link]}`;
}
getYearlySalary(): number {
return 12 * [Link];
}
}

getEmployees(): Observable<Employee[]> {
return [Link]<Employee[]>([Link], { observe: 'body' }).pipe(
map((response: Employee[]) => {
return [Link]((emp: Employee) => {
return new Employee([Link], [Link], [Link], [Link]);
});
})
);
}

Program-50 : HTTP Interceptor Example


=======================================
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
// const myToken = [Link]('myToken');
const myToken = 'ABCDEF123456'
const requestWithToken = [Link]({
setHeaders: {
Authorization: `Bearer ${myToken}`
}
});
return next(requestWithToken);
};
Program-51 : Retry Interceptor
===============================
import { HttpInterceptorFn } from '@angular/common/http';
import { retry } from 'rxjs';
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(retry(1));
};

Program-52 : Loading Interceptor


================================
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { finalize } from 'rxjs';
import { loaderService } from '../services/[Link]';
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
const loaderService = inject(loaderService);
[Link]();

return next(req).pipe(
finalize(() => [Link]()),
);
}

Program-53 : Loading Interceptor


===============================
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private loadingSubject = new BehaviorSubject<boolean>(false);
loading$ = [Link]();
show() {
[Link](true);
}
hide() {
[Link](false);
}
}

program-54 : Error Interceptor


==============================
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { EMPTY, catchError } from 'rxjs';
import { ToastService } from '../services/[Link]';

export const myErrorInterceptor: HttpInterceptorFn = (req, next) => {


const toastService = inject(ToastService);
return next(req).pipe(catchError((error) => {
[Link]([Link]);
return EMPTY;
}));
};

Program-55: Observables
=========================
import { Component } from "@angular/core";
import { Observable, from, interval, range } from 'rxjs';
import { take, filter, map } from 'rxjs/operators';

@Component({
selector: 'app-root',
templateUrl: '[Link]'
})
export class AppComponent {
//Create an observable with given subscription function
createObservable1 = new Observable(function (observer) {
[Link]("aaaaaa");
[Link]("bbbbbb");
[Link]("cccccc");
});
subscriber1 = [Link]({
next: (v) => [Link](v),
error: (e) => [Link](e),
complete: () => [Link]('completed'),
});

//Turn an array or iterable into an observable


arr = [10, 20, 30, 40, 50];
createObservable2 = from([Link]);
testObservable2 = [Link]((ele) => {
[Link](ele) })

// createObservable3 = interval(2000);
//testObservable3 = [Link](val => [Link](val));

createObservable4 = interval(2000);
createObservable4_take = [Link](take(5));
testObservable4 = this.createObservable4_take.subscribe(val => [Link](val));

createObservable5 = range(1, 10)


testObservable5 = [Link](val => [Link](val));

createObservable6 = range(1, 20);


even_numbers = [Link](
filter((ele) => ele % 2 == 0)
)
testObservable6 = this.even_numbers.subscribe((ele) => {
[Link]("even number " + ele)
})
arr2 = [10, 11, 12, 13, 14, 15];
createObservable7 = from(this.arr2);
createObservableSquare = [Link](
map((ele) => ele * ele)
)
testObservableSquare = [Link](
(ele)=>[Link](ele)
)

time = new Observable<string>(observer => {


setInterval(() => [Link](new Date().toString()), 1000);
});

Program-56 : Zip()
====================
zipDemo() {
let publisher1 = of(32, 31, 34);
let publisher2 = of('sanjay', 'sameer', 'bishnu');
let publisher3 = of('bang', 'chennai', 'hyderabad');
let finalPublisher = zip(publisher1, publisher2, publisher3).pipe(
map(([age, name, add]) => ({ age, name, add }))
);

[Link]((data) => [Link](data));


}

program-57 : forkjoin()
========================
fetchDataFromMultipleAPIs() {
let userNames = ['sanjaysamantra1', 'ushamahesh818', 'seun035'];
let requests = [Link](userName => {
return [Link](`[Link]
});
forkJoin(requests).subscribe((responses) => {
[Link](responses);
});
}

Program-58 : MergeMap()
========================
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class TestComponent implements AfterViewInit {

@ViewChild('btn1', { static: true }) button: any;


clickObservable: Observable<any>;
count: number = 0;

constructor() {
[Link] = new Observable();
}

ngAfterViewInit() {
[Link] = fromEvent([Link], 'click');
[Link]();
}

innerObservable(count: number) {
return new Observable((observer) => {
setTimeout(() => { [Link](count + " A") }, 1000);
setTimeout(() => { [Link](count + " B") }, 2000);
setTimeout(() => { [Link](count + " C") }, 3000);
setTimeout(() => { [Link](count + " D") }, 4000);
setTimeout(() => { [Link](count + " E"); [Link]() }, 5000);
})
}

mergeMapExample() {
let obs =
[Link]
.pipe(
mergeMap(() => {
[Link] = [Link] + 1;
return [Link]([Link])
})
)
.subscribe(val => [Link](val));
}
}
-----------------------------
// without mergeMap()
usersPublisher = of(1, 2, 3, 4);
usersSubscriber = [Link]((user) => {
[Link](user);
const url = `[Link]
[Link](url).subscribe((userData) => {
[Link](userData);
});
});

//with mergeMap()
let userPublisher = of(1, 2, 3, 4, 5);
[Link](mergeMap(userId => {
return [Link](`[Link]
})).subscribe(cartResponse => {
[Link](cartResponse)
});
Program-59 : ConcatMap()
===========================
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
import { concatMap } from 'rxjs/operators';

@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class TestComponent implements AfterViewInit {

@ViewChild('btn1', { static: true }) button: any;


clickObservable: Observable<any>;
count: number = 0;

constructor() {
[Link] = new Observable();
}

ngAfterViewInit() {
[Link] = fromEvent([Link], 'click');
[Link]();
}

innerObservable(count: number) {
return new Observable((observer) => {
setTimeout(() => { [Link](count + " A") }, 1000);
setTimeout(() => { [Link](count + " B") }, 2000);
setTimeout(() => { [Link](count + " C") }, 3000);
setTimeout(() => { [Link](count + " D") }, 4000);
setTimeout(() => { [Link](count + " E"); [Link]() }, 5000);
})
}

mergeMapExample() {
let obs =
[Link]
.pipe(
concatMap(() => {
[Link] = [Link] + 1;
return [Link]([Link])
})
)
.subscribe(val => [Link](val));
}

program-60 : TypeAhead using SwitchMap


========================================
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from
'@angular/forms';
import { Observable, switchMap, map } from 'rxjs';

@Component({
selector: 'app-observable-demo3',
standalone: true,
imports: [ReactiveFormsModule, CommonModule],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class ObservableDemo3Component {
searchResult$: Observable<any> | undefined;
searchForm: any;
constructor(private http: HttpClient) {
[Link] = new FormGroup({
searchField: new FormControl()
});
}
ngOnInit() {
[Link]$ = [Link]("searchField").[Link](
switchMap((term) =>
[Link]<any>(`[Link]
),
map((response: any) =>
[Link] > 0 ? [Link] : []
));
}
}

--------------------------------
<div class="jumbotron">
<h1>Search Something</h1>
<form [formGroup]="searchForm">
<input formControlName="searchField" />
</form>
<table class="table bordered">
<tbody>
@for(user of searchResult$ | async ; track $index;){
<tr>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
}
</tbody>
</table>
</div>

program-61 : exhaustMap Example


===============================
@ViewChild('loginBtn') loginBtn!: ElementRef;

ngAfterViewInit() {
fromEvent([Link], 'click').pipe(exhaustMap((val) => {
return [Link]('[Link]
})).subscribe({
next: (res) => [Link]('Response:', res),
error: (err) => [Link]('Error:', err),
})
}

program-62 : distinctUntilChanged Example


============================================
distinctUntilChangedDemo() {
let userIds = of(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3);
[Link](distinctUntilChanged()).subscribe((res) => {
[Link](res);
})
}

distinctUntilChangedWithComparator() {
let user1 = { name: 'sanjay' }
let user2 = { name: 'sanjay' }
let user3 = { name: 'akash' }
let user4 = { name: 'deepak' }
let user5 = { name: 'deepak' }
let users = from([user1, user2, user3, user4, user5]);

[Link](distinctUntilChanged((prev, curr) => [Link] == [Link]))


.subscribe(val => [Link](val));
}

Program-63 : RXJS-Subject Example


===================================
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })

export class MessageService {


private subject = new Subject<any>();

sendMessage(message: string) {
[Link]({ text: message });
}

clearMessages() {
[Link](null);
}

getMessage(): Observable<any> {
return [Link]();
}
}
--------
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../[Link]';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-rxjs',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class RxjsComponent implements OnInit {
messages: any[] = [];
subscription: Subscription;

constructor(private messageService: MessageService) {


[Link] = new Subscription();
}
ngOnInit() {
// subscribe to messages subject-observable
[Link] = [Link]().subscribe(message => {
if (message) {
[Link](message);
} else {
// clear messages when empty message received
[Link] = [];
}
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
[Link]();
}
}
---------
<p>rxjs works!</p>
<table border=2 width=50% align=center>
@for (msg of messages; track msg) {
<tr>
<td>{{[Link]}}</td>
</tr>
}
</table>
--------------
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../[Link]';

@Component({
selector: 'app-rxjs2',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class Rxjs2Component implements OnInit {
newMsg

constructor(private messageService: MessageService) { }


ngOnInit() { }

sendMessage(): void {
// send message to subscribers via observable subject
[Link]([Link]);
}
clearMessages(): void {
// clear messages
[Link]();
}

}
----------
<p>rxjs2 works!</p>
<input type="text" [(ngModel)]='newMsg'>
<button (click)='sendMessage()'>send message</button>
<button (click)='clearMessages()'>Clear Message</button>

Program-64 : RXJS Behaviour-Subject Example


============================================
[Link]
---------------
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export interface Todo {
id: any;
value: string;
}
const initialTodos = [
{ id: 1, value: 'Todo 1' },
{ id: 2, value: 'Todo 2' },
];
@Injectable({
providedIn: 'root',
})
export class TodoService {
private todoSubject = new BehaviorSubject<Todo[]>(initialTodos);
readonly todoObs = [Link]();

private todosArr: Todo[] = initialTodos;


private nextId = 2;
create(item: Todo) {
[Link] = ++[Link];
[Link](item);
[Link]([Link]([], [Link]));
}
remove(id: number) {
[Link]((todo, ind) => {
if ([Link] === id) {
[Link](ind, 1);
}
[Link]([Link]([], [Link]));
});
}
}

[Link]
---------------------
import { Component, OnInit } from '@angular/core';
import { TodoService } from '../[Link]';
@Component({
selector: 'app-todo-add',
template: `
<div>
<h3>Add Todo</h3>
<input #addToDo /> &nbsp;
<button (click)="addNewTodo(addToDo)">Add New Todo</button>
</div>
`,
})
export class TodoAddComponent implements OnInit {
constructor(private todoService: TodoService) {}
ngOnInit(): void {}
addNewTodo(todoText: string) {
[Link]({ id: 3, value: todoText });
}
}

[Link]
----------------------
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Todo, TodoService } from '../[Link]';

@Component({
selector: 'app-todo-list',
template: `
<h3>Todo List</h3>
<div *ngFor="let todo of todos$ | async">
{{ [Link] }} {{ [Link] }}
<button (click)="deleteTodo([Link])">x</button>
</div>
`,
})
export class TodoListComponent implements OnInit {
todos$!: Observable<any>;
constructor(private todoService: TodoService) {}
ngOnInit(): void {
[Link]$ = [Link];
}
deleteTodo(id: number) {
[Link](id);
}
}

Program-65 : RXJS Behaviour-Subject Cart Details


=================================================
[Link]
---------------
export class CartService {
private cartItemSubject = new BehaviorSubject([]);
cartItem$ = [Link]();
private totalPriceSubject = new BehaviorSubject(0);
totalPrice$ = [Link]();

addItem(newItem: any) {
const cartItems: any = [Link];
[Link](newItem);
[Link](cartItems);
[Link]();
}
removeItem(itemToRemove: any) {
const cartItems: any = [Link];
const cartItemsAfterRemove = [Link]((cartItem: any) => {
return [Link] !== [Link];
});
[Link](cartItemsAfterRemove);
[Link]();
}
calculateTotalPrice() {
const cartItems: any = [Link];
let totalPrice = 0;
[Link]((cartItem: any) => {
totalPrice = totalPrice + [Link];
});
[Link](totalPrice);
}
}

[Link]
-------------------
export class HeaderComponent {
cartItems: any[] = [];
totalPrice: number = 0;
subscriptionsArr: Subscription[] = [];
constructor(private CartService: CartService) {
let cartItemSubscription = [Link]$.subscribe(cartItems => {
[Link] = cartItems;
});
[Link](cartItemSubscription);

let totalPriceSubscription = [Link]$.subscribe(totalPrice


=> {
[Link] = totalPrice;
});
[Link](totalPriceSubscription);
}

ngOnDestroy() {
[Link](subscription => {
[Link]();
})
}
}
Program-66 : Signal
====================
export class SignalDemoComponent {
num: WritableSignal<number> = signal(0);
messages: WritableSignal<string[]> = signal([]);
numDouble: Signal<number> = computed(() => [Link]() * 2);
numSquare: Signal<number> = computed(() => [Link]() * [Link]());

increment() {
[Link]((value: number) => value + 1)
[Link]([...[Link](), `Value of Num is: ${[Link]()}`]);
}
decrement() {
[Link]((val: number) => val - 1);
[Link]().pop()
[Link]([... [Link]()]);
}
reset() {
[Link](0);
[Link]([]);
}
}
-----------------------
<h3 class="text-center">Signal Demo</h3>
<div class="border">
<h4>Num value is {{num()}}</h4>
<h4>Square value is {{numSquare()}}</h4>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()" class="m-1">Reset</button>
<button (click)="increment()">Increment</button>
<hr/>
@for(msg of messages();track $index){
<div>{{msg}}</div>
}
</div>

Program-67 : effects
======================
userId = signal(1);
userData: any;
userDetailsEffect = effect(() => {
const id = [Link]();
[Link](id);
});
destroyEffect() {
[Link]()
}
constructor(private httpClient: HttpClient) {
}
fetchUserDetails(id: number) {
[Link](`[Link]
{id}`).subscribe(response => {
[Link] = response;
})
}
incrementUserId() {
[Link](val => val + 1);
}

program-68: Form with Class Names


====================================
<form name='myForm'>
Name:
<input name='uname' [(ngModel)]='name' required /><br><br>
Age:
<input name='uage' [(ngModel)]='age' />
</form>

<style>
[Link]-invalid{
border:5px solid red;
}
[Link]-valid{
border:5px solid green;
}
</style>

program-69 : template driven form Example


==========================================
<form #myForm="ngForm" (ngSubmit)="logForm([Link])">
<label>Firstname:</label>
<input type="text" name="firstname" ngModel>

<label>Lastname:</label>
<input type="text" name="lastname" ngModel>

<div ngModelGroup='address'>
<label>Street:</label>
<input type="text" name="street" ngModel>

<label>pin:</label>
<input type="text" name="zip" ngModel>

<label>City:</label>
<input type="text" name="city" ngModel>
</div>

<button type="submit">Submit</button>
</form>
<h2> {{ [Link] | json }} </h2>

program-70 : Template Driven form with Validation


==================================================
<h1 class="text-center">Template Driven Form</h1>

<form #myForm="ngForm" (submit)="submitMyForm(myForm)">


<div>
First Name: <input #fname="ngModel" name="firstName" ngModel required
minlength="5" />

<span class="text-danger" *ngIf="[Link]('required') &&


[Link]">FirstName is required</span>
<span class="text-danger" *ngIf="[Link]('minlength') &&
[Link]">FirstName should have minimum 5
characters</span>
</div>
<div>
Last Name: <input #lname="ngModel" name="lastName" ngModel required
minlength="5" />

<span class="text-danger" *ngIf="lname?.errors?.['required'] &&


[Link]">lastName is required</span>
<span class="text-danger" *ngIf="lname?.errors?.['minlength'] &&
[Link]">minimum 5 chars</span>
</div>
<div>
Email: <input #email="ngModel" name="email" ngModel required email />
</div>
<fieldset ngModelGroup="address">
<div>
Street Name: <input #street="ngModel" name="street" ngModel />
</div>
<div>
City: <input #city="ngModel" name="city" ngModel />
</div>
<div>
PIN: <input #pin="ngModel" name="pin" ngModel />
</div>
</fieldset>

<button type="submit" [disabled]="[Link]" >Submit</button>


<button type="reset">reset</button>
</form>

<h3>{{[Link] | json}}</h3>

<h3>{{[Link]}}</h3>
<div>{{[Link] | json}}</div>
<div>{{[Link] | json}}</div>

<div></div>

program-71 : Template Driven Form with validation


=================================================
<h1>template driven Form with validation</h1>

<form name="myForm1" #myForm="ngForm" (submit)="submitMyForm([Link])">


name:
<input name="name" #name="ngModel" [(ngModel)]="[Link]" required
pattern="[a-zA-Z]+" />
<span *ngIf="[Link]('required') && [Link]" class="text-danger">Name
is required</span>
<span *ngIf="[Link]('pattern') && [Link]" class="text-danger">Only
alphabets allowed</span>
<br><br>
age:
<input name="age" #age="ngModel" [(ngModel)]="[Link]" required pattern="[0-9]
{2}" />
<span *ngIf="[Link]('required') && [Link]" class="text-danger">Age is
required</span>
<span *ngIf="[Link]('pattern') && [Link]" class="text-danger">Only
Numbers allowed</span>
<br><br>

<input type="submit" [disabled]="[Link]" />

</form>
<hr>
<div> Form Value: {{ [Link] | json }}</div>
<div> Form Valid Status: {{ [Link] | json }} </div>

<div>Name Value: {{[Link]}}</div>


<div>Age Value: {{[Link]}}</div>

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

@Component({
selector: 'app-template',
templateUrl: './[Link]',
styles: [
'[Link]-dirty{border:2px solid red}'
]
})
export class TemplateComponent {
submitMyForm(user: any) {
alert(`Name: ${[Link]} Age: ${[Link]}`);
}
user: any = { name: 'sanjay', age: 44 };
}

program-72 : Model driven form example


=======================================
<form [formGroup]="registerForm">
<label>Firstname:</label>
<input type="text" formControlName="firstname">

<label>Lastname:</label>
<input type="text" formControlName="lastname">
<div formGroupName='address'>
<label>Street:</label>
<input type="text" formControlName="street">

<label>Zip:</label>
<input type="text" formControlName="zip">

<label>City:</label>
<input type="text" formControlName="city">
</div>

<button type="submit">Submit</button>
</form>
<h2>{{[Link] | json}}</h2>

*****************
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'my-app',
...
})
export class AppComponent {

registerForm = new FormGroup({


firstname: new FormControl(),
lastname: new FormControl(),
address: new FormGroup({
street: new FormControl(),
zip: new FormControl(),
city: new FormControl()
})
});
}

program-73 : Model driven form with validation


===============================================
<div>
<h2> Model Driven Forms </h2>
<hr>
<form [formGroup]="myForm" (submit)="submitMyForm()">
Name:
<input pattern='[a-z]+' id="name" formControlName="name" required>
<span *ngIf="[Link]('required') &&
[Link]"> Name Required </span>
<span *ngIf="[Link]('pattern') &&
[Link]"> Wrong Pattern </span>
<br><br>

Age:
<input id="age" formControlName="age">
<br><br>

Address:
<input id="address" formControlName="address" >
<span *ngIf="[Link]('required') && [Link]"> Address is
Required </span>
<span *ngIf="[Link]('minlength') && [Link]"> Min 5
characters Required </span>
<span *ngIf="[Link]('maxlength') && [Link]"> max 10
characters allowed </span>
<br><br>

<button type="submit" [disabled]="![Link]">Submit</button>


&nbsp;
<button type="reset"> Reset </button>

</form>
<hr>
<div> Form Value: {{[Link] | json }} </div>
<div> Form Status:{{[Link] | json }} </div>
</div>
***************
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: '[Link]'
})
export class AppComponent {
myFormBuilder;
myForm;

constructor() {
[Link] = new FormBuilder();
[Link]();
}

get age() {
return [Link]('age')
}
get address() {
return [Link]('address')
}
generateForm() {
let formControlObj1 = new FormControl('sachin', [[Link],
[Link]('[a-zA-z]+')]);
let formControlObj2 = new FormControl('35');
let formControlObj3 = new FormControl('mumbai', {
validators : [[Link],[Link]('[a-zA-z]+')],
updateOn : 'blur'
});

[Link] = [Link]({
name: formControlObj1,
age: formControlObj2,
address: formControlObj3
})
}

submitMyForm() {
alert(`Name: ${[Link]} Age: ${[Link]} Address: $
{[Link]}`);
}
}
program-74 : dynamic Form
=============================
import { Component } from '@angular/core';
import { FormGroup, FormArray, FormBuilder } from '@angular/forms';

@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
empForm!: FormGroup;
constructor(private fb: FormBuilder) { }

ngOnInit() {
[Link] = [Link]({
employees: [Link]([])
});
}

getAllEmployees(): FormArray {
return [Link]('employees') as FormArray;
}

createNewEmployee(): FormGroup {
return [Link]({
firstName: '',
lastName: '',
skills: [Link]([])
});
}

addEmployee() {
[Link]().push([Link]());
}

removeEmployee(empIndex: number) {
[Link]().removeAt(empIndex);
}

employeeSkills(empIndex: number): FormArray {


return [Link]().at(empIndex).get('skills') as FormArray;
}

newSkill(): FormGroup {
return [Link]({skill: '',exp: ''});
}

addEmployeeSkill(empIndex: number) {
[Link](empIndex).push([Link]());
}

removeEmployeeSkill(empIndex: number, skillIndex: number) {


[Link](empIndex).removeAt(skillIndex);
}

onSubmit() {
[Link]([Link]);
}
}
----------------------------------
<style>
button {
margin: 5px
}
</style>
<h1>Angular Nested FormArray / Dynamic FormArray</h1>
<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
<div formArrayName="employees">
<div *ngFor="let employee of getAllEmployees().controls; let
empIndex=index">
<div [formGroupName]="empIndex" style="border: 2px solid blue; padding:
10px; width: 700px; margin: 10px;">
{{empIndex}} First Name :
<input type="text" formControlName="firstName" />
Last Name:
<input type="text" formControlName="lastName" />

<button (click)="removeEmployee(empIndex)">Remove</button>

<div formArrayName="skills">
<div *ngFor="let skill of employeeSkills(empIndex).controls;
let skillIndex=index">
<div [formGroupName]="skillIndex">
{{skillIndex}} Skill :
<input type="text" formControlName="skill" />
Exp:
<input type="text" formControlName="exp" />

<button
(click)="removeEmployeeSkill(empIndex,skillIndex)">
Remove
</button>
</div>
</div>
</div>
<button type="button" (click)="addEmployeeSkill(empIndex)">
Add Skill
</button>
</div>
</div>
<button type="button" (click)="addEmployee()">Add Employee</button>
</div>
</form>

<pre>{{[Link] | json}}</pre>

program-75 : Custom Validation


================================

createPasswordStrengthValidator
---------------------------------
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function createPasswordStrengthValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = [Link];
if (!value) {
return null;
}
const hasUpperCase = /[A-Z]+/.test(value);
const hasLowerCase = /[a-z]+/.test(value);
const hasNumeric = /[0-9]+/.test(value);
const passwordValid = hasUpperCase && hasLowerCase && hasNumeric;
return !passwordValid ? { passwordStrength: true } : null;
}
}

ageRangeValidator
=================
import { AbstractControl, ValidatorFn } from "@angular/forms";
function ageRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if ([Link] !== undefined && (isNaN([Link]) || [Link] <
min || [Link] > max)) {
return { 'ageRange': true };
}
return null;
};
}

Async validator
================
userService
-----------
findUserByEmail(email: string) {
return [Link](`[Link]
{email}`)
}

[Link]
----------------------
import { inject } from "@angular/core";
import { AbstractControl, AsyncValidatorFn } from "@angular/forms";
import { map } from "rxjs";
import { UserService } from "../services/[Link]";
export function userExistsValidator(): AsyncValidatorFn {
const userService = inject(UserService);
return (control: AbstractControl) => {
return [Link]([Link]).pipe(
map((user: any) => [Link] ? { userExists: true } : null)
);
}
}

Program-76 : Password Generator


================================
<div class="container">
<h2>🔐 Angular Password Generator</h2>

<label>
Length:
<input type="number" [(ngModel)]="length" min="4" max="50">
</label>

<label>
<input type="checkbox" [(ngModel)]="includeUppercase" />
Uppercase (A-Z)
</label>

<label>
<input type="checkbox" [(ngModel)]="includeLowercase" />
Lowercase (a-z)
</label>

<label>
<input type="checkbox" [(ngModel)]="includeNumbers" />
Numbers (0-9)
</label>

<label>
<input type="checkbox" [(ngModel)]="includeSymbols" />
Symbols (!@#$)
</label>

<button (click)="generatePassword()">Generate Password</button>

<div class="output">
<p>{{ password }}</p>
<button (click)="copyToClipboard()">📋 Copy</button>
</div>
</div>
------------------------------
length: number = 8;
includeUppercase: boolean = true;
includeLowercase: boolean = true;
includeNumbers: boolean = true;
includeSymbols: boolean = false;

password: string = '';

generatePassword() {
const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const lower = 'abcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';

let validChars = '';


if ([Link]) validChars += upper;
if ([Link]) validChars += lower;
if ([Link]) validChars += numbers;
if ([Link]) validChars += symbols;

if (!validChars) {
[Link] = '⚠️ Select at least one option';
return;
}

let generated = '';


for (let i = 0; i < [Link]; i++) {
const index = [Link]([Link]() * [Link]);
generated += validChars[index];
}

[Link] = generated;
}

copyToClipboard() {
[Link]([Link]);
alert('Password copied to clipboard!');
}

program-77 : routing
=====================
1. Specify the Base URL: <base href="/"> in [Link]
2. Import RouterModule from '@angular/router'
3. Define the routes

[Link]
-------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './[Link]';


import { HomeComponent } from './home/[Link]';
import { AboutusComponent } from './aboutus/[Link]';
import { CareerComponent } from './career/[Link]';

import { appRoutes } from './routerConfig'

@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutusComponent,
CareerCompon ent,
],
imports: [
BrowserModule, [Link](appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

[Link]
----------------
import { Routes } from '@angular/router';
import { HomeComponent } from './home/[Link]';
import { AboutusComponent } from './aboutus/[Link]';
import { CareerComponent } from './career/[Link]';

export const appRoutes: Routes = [

{
path: 'home',
component: HomeComponent
},
{
path: 'aboutUs',
component: AboutusComponent
},
{
path: 'career',
component: CareerComponent
},
{
path: '',
//redirectTo: 'home',
component:HomeComponent,
//pathMatch: 'full'
},
{
path: '**',
component: notFoundComponent
}
]

[Link]
-------------------
<div style="text-align: center">
<h1>This is {{title}}</h1>
<nav>
<a routerLink="home">Home</a> <br><br>
<a routerLink="aboutUs">About Us</a> <br><br>
<a routerLink="career">Career</a>
</nav>
<hr>
<router-outlet></router-outlet>
</div>

N.P:- Create 3 components


ng g c home
ng g c aboutUs
ng g c career

Program-78 : Path-Param Example


==============================
1. create productDetailsComponent
ng g c productDetails

2. add the below code in [Link]


{
path: 'productdetails/:id',
component: ProductdetailsComponent
}

3. add the below code in [Link]


<button class="btn btn-primary" [routerLink]="['/productdetails', [Link]]">
View Details</button>

4. add the below code in [Link]


constructor(private activatedRoute: ActivatedRoute)
{
}
ngOnInit() {
[Link](params => {
[Link] = +params['id']; // (+) converts string 'id' to a number
// In a real app: make Http call to get the details
});
}

5. add the below code in [Link]


<h1>This is details for product- {{id}}

program-79 : Query-param example


=================================
1. create a new route and add in route configuration
{
path: 'productdetails',
component: ProductdetailsComponent
}

2. add the below code in [Link]


<button class="btn btn-primary" [routerLink]="['/productdetails']"
[queryParams]="{id:[Link],name:[Link],price:[Link]}">
View Details</button>

3. add the below code in [Link]


constructor(public activatedRoute: ActivatedRoute) {
}
ngOnInit(){
[Link]((queryparams) => {
[Link](queryparams);
[Link] = queryparams;
});
}

Program-80 : Router Guard


==========================
import { CanActivateFn } from '@angular/router';
export const authGuard: CanActivateFn = (route, state) => {
// Inject user service, Read user info from user service
const user = { name: 'sanjay', role: 'admin1' };
if ([Link] === 'admin') {
return true;
} else {
alert('Sorry!!! You dont have access to this page')
return false;
}
};

{
path: 'product-details',
component: ProductDetailsComponent,
canActivate: [myGuard]
},

can-deactivate
==============
import { CanDeactivateFn } from '@angular/router';
export const hasChangesGuard: CanDeactivateFn<unknown> =
(component: any, currentRoute, currentState, nextState) => {
if (component?.isDirty) {
alert('Please save your changes before you leave this route');
return false;
} else {
return true
}
};

program-81 : Route resolver Example


=====================================
1. create ProductService and add the below code

import { HttpClient } from '@angular/common/http';


import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(public http: HttpClient) { }
getProductDetails(id: number) {
const url = `[Link]
return [Link](url);
}
}

2. create productdetailResolver and add the below code

import { HttpClient } from '@angular/common/http';


import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { ProductService } from '../services/[Link]';
export const productdetailsResolver: ResolveFn<Object> = (route, state) => {
const id = +[Link]['id'];
return inject(ProductService).getProductDetails(id);
};

3. add the below code in [Link]


{
path: 'productdetails/:id',
component: ProductdetailsComponent,
resolve: { product: productdetailsResolver }
}
4. Add the below code in [Link]

constructor(private activatedRoute: ActivatedRoute) { }


ngOnInit() {
[Link]( [Link])
[Link]((response: any) => {
[Link] = [Link]; // to be shown in UI
});
}

Program-82 : Folder Explorer(Folder-Emoji)


===========================================
import { CommonModule } from '@angular/common';
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-folder-explorer',
standalone: true,
imports: [CommonModule],
templateUrl: './[Link]',
styleUrl: './[Link]',
inputs: ['folderObj']
})
export class FolderExplorerComponent {
folderObj: any;
isExpanded: boolean = false;
}
---------------------------
@if ([Link]) {
<div (click)="isExpanded=!isExpanded" style="cursor:pointer">
📁 <span>{{ [Link] }}</span>
</div>
@if (isExpanded) {
<div style="padding-left: 20px;">
@for (item of [Link]; track item) {
<div>
<app-folder [folderObj]="item"></app-folder>
</div>
}
</div>
}
}@else{
<div>
📑 <span>{{ [Link] }}</span>
</div>
}
Program-83 : traffic Application
=================================
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-traffic-signal',
standalone: true,
imports: [CommonModule],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class TrafficSignalComponent {
config: any;
colorsArr: string[];
selectedColor: string = 'red';
timer: any;
constructor() {
[Link] = {
"red": { nextColor: 'green', duration: 4000 },
"green": { nextColor: 'yellow', duration: 3000 },
"yellow": { nextColor: 'red', duration: 1000 }
};
[Link] = [Link]([Link]);
}
ngDoCheck() {
const { duration, nextColor } = [Link][[Link]];
[Link] = setTimeout(() => {
[Link] = nextColor;
}, duration)
}
ngOnDestroy() {
clearTimeout([Link]);
}
}

===============
<div class="wrapper">
<div class='traffic-light-container traffic-light-container--vertical'>
@for (color of colorsArr; track color) {
<div class="traffic-light" [[Link]-color]="color ===
selectedColor ? selectedColor:'' ">
</div>
}
</div>
</div>
=================
.wrapper {
display: flex;
align-items: center;
flex-direction: column;
gap: 16px;
justify-content: center;
}
.traffic-light-container {
background-color: #000;
border-radius: 8px;
display: flex;
padding: 8px;
gap: 8px;
}
.traffic-light-container--vertical {
flex-direction: column;
}
.traffic-light {
background-color: #555;
border-radius: 50px;
height: 50px;
width: 50px;
}

Program-84 : jasmine karma


==========================
import { JasmineComponent } from './[Link]';

describe('I am testing Jasmine component', () => {


var obj = new JasmineComponent();

it('I am testing add method', () => {


expect([Link](2, 3)).toBe(5);
})
it('I am testing sub method', () => {
expect([Link](2, 3)).toBe(-1);
})
it('I am testing even method', () => {
expect([Link](8)).toBe(true);
expect([Link](3)).toBe(false);
})
it('I am testing odd method', () => {
expect([Link](8)).toBe(false);
expect([Link](13)).toBe(true);
})
})
****************
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-jasmine',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class JasmineComponent implements OnInit {

constructor() { }

ngOnInit() {
}

public add(a, b) {
return a + b;
}
public sub(a, b) {
return a - b;
}
public isNumberEven(num){
return num%2 === 0;
}
public isNumberOdd(num){
return num%2 !== 0;
}
}

Program-85 : Testing Service with HttpClient


================================================
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from
'@angular/common/http/testing';
import { UserService } from './[Link]';

describe('UserService', () => {
let service: UserService;
let httpTestingController: HttpTestingController;

beforeEach(() => {
[Link]({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
]
});
service = [Link](UserService);
httpTestingController = [Link](HttpTestingController);
});
afterEach(() => {
// Ensure no outstanding requests
[Link]();
});

it('user service should be created', () => {


expect(service).toBeTruthy();
});
it('should fetch data using GET request', () => {
const dummyUsers = [
{ id: 1, name: 'Leanne Graham' },
{ id: 2, name: 'Ervin Howell' }
];
[Link]().subscribe(users => {
expect(users).toEqual(dummyUsers);
expect([Link]).toBe(2);
});
// Expect the GET request
const req =
[Link]('[Link]
expect([Link]).toBe('GET');
// Respond with mock data
[Link](dummyUsers);
});
});
Testing Component with HttpClient
==================================
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserListComponent } from './[Link]';
import { provideHttpClient } from '@angular/common/http';
import { UserService } from '../../services/[Link]';
import { of } from 'rxjs';
describe('UserListComponent', () => {
let component: UserListComponent;
let fixture: ComponentFixture<UserListComponent>;
let userService : UserService;

beforeEach(async () => {
await [Link]({
imports: [UserListComponent],
providers: [
provideHttpClient(),
UserService
]
})
.compileComponents();

fixture = [Link](UserListComponent);
component = [Link];
[Link]();
userService = [Link](UserService)
});

it('should verify getAllUsers', () => {


const mockresponse: any[] = [{}, {}];
spyOn(userService, 'getAllUsers').[Link](of(mockresponse));
[Link]();
[Link]();
expect([Link]).toBe(2);
});
});

Stub & Spy Demo


===============
class WeatherService {
getTemperature(city) {
// Simulate an API call
throw new Error("Real API call not implemented");
}
}
class WeatherProcessor {
constructor(weatherService) {
[Link] = weatherService;
}
isHot(city) {
const temperature = [Link](city);
return temperature > 30; // Hot if temperature > 30°C
}
}
------------------------
describe("WeatherProcessor", function () {
let weatherService, weatherProcessor;

beforeEach(function () {
weatherService = new WeatherService();
weatherProcessor = new WeatherProcessor(weatherService);
});

it("should determine if the weather is hot using a stubbed temperature", function


() {
// Stub the getTemperature method
spyOn(weatherService, "getTemperature").[Link](35);

const result = [Link]("New York");

// Verify results
expect([Link]).toHaveBeenCalledWith("New York");
expect(result).toBe(true); // 35 > 30, so it's hot
});

it("should determine if the weather is not hot using a stubbed temperature",


function () {
// Stub the getTemperature method
spyOn(weatherService, "getTemperature").[Link](20);

const result = [Link]("London");

// Verify results
expect([Link]).toHaveBeenCalledWith("London");
expect(result).toBe(false); // 20 < 30, so it's not hot
});

it("should track how many times getTemperature is called", function () {


// Spy on the getTemperature method without changing behavior
spyOn(weatherService, "getTemperature").[Link](() => 25);

[Link]("Paris");
[Link]("Berlin");

// Verify spy tracking


expect([Link]).toHaveBeenCalledTimes(2);
expect([Link]).toHaveBeenCalledWith("Paris");
expect([Link]).toHaveBeenCalledWith("Berlin");
});
});

Program-86 : Counter App using NgRx


=================================
1. Install NgRx Store in the project
ng add @ngrx/store

2. Create action File ([Link])


import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');
3. Create Reducer File([Link])
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from '../actions/[Link]';
export const initialState = 0;
export const counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
4. Provide the Store to the whole application([Link])
providers: [
provideStore({ count: counterReducer })
]

5. Create Counter Component ([Link])


count$: Observable<number>;
constructor(private store: Store<{ count: number }>) {
[Link]$ = [Link]('count');
[Link]([Link]$)
}
increment() {
[Link](increment())
}

6. [Link]
<h2>Count value is : {{count$ | async}}</h2>
<button (click)="increment()">Increment</button>

Program-87 : ToDo App using NgRx


=================================
1. Install NgRx Store in the project
ng add @ngrx/store

2. Create action File ([Link])


import { createAction, props } from '@ngrx/store';
import { Todo } from '../../models/todo';
export const addTodo = createAction('Add Todo', props<{ payload: Todo }>());
export const deleteTodo = createAction('Delete Todo', props<{ id:
number }>());
export const toggleTodo = createAction('Toggle Todo', props<{ id:
number }>());

3. Create Reducer File([Link])


import { createReducer, on } from '@ngrx/store';
import { addTodo, deleteTodo, toggleTodo } from '../actions/[Link]';
export const initialState = [
{ id: 1, text: 'Learn javascript', isCompleted: true },
{ id: 2, text: 'Go to Gym', isCompleted: false },
{ id: 3, text: 'Buy Grocery', isCompleted: false },
];
export const todoReducer = createReducer(
initialState,
on(addTodo, (state, action: any) => {
return [...state, [Link]]
}),
on(deleteTodo, (state, action: any) => {
return [Link](todo => [Link] != [Link]);
}),
on(toggleTodo, (state, action: any) => {
return [Link]((todo) => {
return [Link] !== [Link]
? todo
: { ...todo, isCompleted: ![Link] }
});
})
);
4. Provide the Store to the whole application([Link])
providers: [
provideStore({ todoArr:todoReducer })
]

5. Create ToDoCrud Component ([Link])


todos$: Observable<any> | undefined;
constructor(private store: Store) {
[Link]$ = [Link]((state: any) => [Link]);
}
deleteMyTodo(id: number) {
[Link](deleteTodo({ id: id }));
}
toggleMyTodo(id: number) {
[Link](toggleTodo({ id: id }));
}

6. [Link]
<h3 class="text-center">This is Todo CRUD Component using NGRX</h3>
<div class="border p-2 text-center col-sm-4 offset-4">
<ol>
@for(todo of todos$|async;track $index){
<li class="my-2">
<span [ngStyle]="{ 'text-decoration': [Link] ?
'line-through' : 'none' }">{{[Link]}} &nbsp; {{[Link]}}
&nbsp;</span>
<button class="btn btn-danger"
(click)="deleteMyTodo([Link])">Delete</button>
<button class="btn btn-secondary mx-1"
(click)="toggleMyTodo([Link])">Toggle</button>
</li>
}
</ol>
</div>

Program-88 : Employee CRUD using NgRx


=====================================
1. Install Store & Effect in the project
ng add @ngrx/store
ng add @ngrx/effects

2. Create action File ([Link])


import { createAction, props } from '@ngrx/store';
import { Employee } from '../models/employee';
export const fetchEmployees = createAction('[EmployeeList Page] Fetch
Employees');
export const fetchEmployeesSucess = createAction(
'[Employees API] Employees Loaded Successfully',
props<{ payload: Employee[] }>()
);
export const fetchEmployeesError = createAction('[Employees API] Employees
Loaded Error');
export const deleteEmployee = createAction(
'[Employees API] Delete Employee',
props<{ id: string }>()
);
export const addEmployee = createAction(
'[Employees API] Add Employee',
props<{ employee:Employee }>()
);

3. Create Reducer File([Link])


import { createReducer, on } from '@ngrx/store';
import { fetchEmployeesSucess } from './[Link]';
export const initialState = [];
export const employeesReducer = createReducer(
initialState,
on(fetchEmployeesSucess, (state, action: any) => {
return [Link];
}),
);

4. Create Effect File ([Link])


import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, exhaustMap, catchError } from 'rxjs/operators';
import { EmployeeService } from '../services/[Link]';
import { addEmployee, deleteEmployee, fetchEmployees } from
'./[Link]';
@Injectable()
export class EmployeeEffects {
loadEmployees$: any;
deleteEmployee$: any;
addEmployee$: any;
constructor(
private actions$: Actions,
private employeeService: EmployeeService
) {
[Link]$ = createEffect(() => [Link]$.pipe(
ofType(fetchEmployees),
exhaustMap(() => [Link]()
.pipe(
map(Employees =>
({ type: '[Employees API] Employees Loaded Successfully',
payload: Employees })
),
catchError(() => of({ type: '[Employees API] Employees Loaded
Error' }))
))
));
[Link]$ = createEffect(() => [Link]$.pipe(
ofType(deleteEmployee),
exhaustMap((action: any) =>
[Link]([Link])
.pipe(
map(Employee => {
alert('Employee Deleted Succesfully');
return ({ type: '[EmployeeList Page] Fetch Employees' })
}),
catchError(() => of({ type: '[Employees API] Employee Delete
Error' }))
))
));
[Link]$ = createEffect(() => [Link]$.pipe(
ofType(addEmployee),
exhaustMap((action: any) =>
[Link]([Link])
.pipe(
map(Employee => {
alert('Employee Added Succesfully');
return ({ type: '[EmployeeList Page] Fetch Employees' })
}),
catchError(() => of({ type: '[Employees API] Employee Add
Error' }))
))
));
}

5. Provide the Store & effect([Link])


providers: [
provideStore({ employees: employeesReducer }),
provideEffects(EmployeeEffects)
]

6. Add Employee-list and add-employee component


employees$: Observable<Employee[]> = [Link](state =>
[Link]);
constructor(private store: Store<{ employees: Employee[] }>) {
}
ngOnInit() {
[Link]({ type: '[EmployeeList Page] Fetch Employees' });
// [Link](fetchEmployees());
}
deleteEmp(id: string) {
const flag = confirm('Are you sure, You want to delete this record?')
if (flag) {
[Link](deleteEmployee({ id }));
}
}

Program-89 : angular & GraphQL


===============================
1. install apollo-angular
ng add apollo-angular

2. in [Link] add backend URL


uri: '[Link]

3. add the below code in component


import { Apollo, gql } from 'apollo-angular';

comments: any;
constructor(private readonly apollo: Apollo) { }
ngOnInit() {
const GET_COMMENTS = gql`
query comments {
comments {
id
name
}
}
`;
const queryRef = [Link]<any>({ query: GET_COMMENTS });
[Link]((response: any) => {
[Link] = [Link];
[Link]([Link])
});
}

4. use the data in HTML file


<div *ngFor="let data of comments">
{{[Link]}}-{{[Link]}}
</div>

program-90 : Cypress Testing


==============================
describe('My First Test', () => {
it('Visits the initial project page', () => {
[Link]('/')
[Link]('Databinding Component')
[Link]().should('eq', 'AngularProjectOct2024');
[Link]('#box1').should('exist');
[Link]('#box2').should('exist');
[Link]('#box3').should('[Link]');
})
it('Should verify addition functionality', () => {
[Link]('/')
[Link]('#box1').type('10');
[Link]('#box2').type('20');
[Link]('#addition').click();
[Link]('Addition of 10 & 20 is 30')
[Link]('#box1').type('0');
[Link]('#box2').type('0');
[Link]('#addition').click();
[Link]('Addition of 100 & 200 is 300')
})
})

Program-91 : App_Initializer
=============================
1. Create a Configuration Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ConfigService {
private config: any;
constructor() {}
loadConfig(): Promise<void> {
// Simulate an async operation like an HTTP request
return new Promise((resolve, reject) => {
setTimeout(() => {
[Link] = { apiUrl: '[Link] featureFlag: true };
[Link]('Configuration loaded:', [Link]);
resolve();
}, 1000);
});
}
getConfig(): any {
return [Link];
}
}

2. Use APP_INITIALIZER to Load Config ([Link])


providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [ConfigService],
multi: true
}
]

3. Access Config in Your Components


import { Component, OnInit } from '@angular/core';
import { ConfigService } from './services/[Link]';

@Component({
selector: 'app-root',
template: `
<h1>Angular 19 APP_INITIALIZER Example</h1>
<p>Check the console for loaded configuration!</p>
`,
})
export class AppComponent implements OnInit {
constructor(private configService: ConfigService) {}

ngOnInit(): void {
const config = [Link]();
[Link]('Config in component:', config);
}
}

You might also like