Angular Programs
Angular Programs
-----------------------
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-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.
<button (click)="add([Link],[Link])">Add</button>
</div>`
})
export class AppComponent {
add(a,b){
alert(Number(a)+Number(b));
}
}
<head>
<meta charset="utf-8">
<title>MyProject1</title>
<base href="/">
}
</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 {
@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>
----------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-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-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>
@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] = 'red';
} else {
[Link] = 'cyan';
}
}
}
******************
<input type="text" numberonly name="salary" id="salary">
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
@HostListener('click')
clickHandler(e) {
[Link]();
}
}
@HostListener('mouseleave') onMouseLeave() {
[Link]([Link], [Link]);
}
}
searchText = [Link]();
return [Link](item => {
return [Link](item).toLowerCase().includes(searchText);
});
}
}
@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], '$');
}
ex:
@Pipe({
name: 'myCustomPipe',
pure: true/false
})
Original array:
<span *ngFor="let digit of originalList">
<b>{{digit}}</b>,
</span><hr>
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)
}
}
<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>
a: number = 15;
b: string = "hiiiiii";
sendA():void{
[Link](this.a);
}
sendB():void{
[Link](this.b);
}
}
<div class="container">
<div class="row">
@for(categoryObj of allCategories;track $index){
<div class="col">
<app-category [categoryObj]="categoryObj"></app-category>
</div>
}
</div>
</div>
.category img{
width:65px;
height:65px;
}
.category div{
font-size: 12px;
font-weight: 700;
}
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>
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 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]();
@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);
}
}
@Component({
selector: 'app-root',
templateUrl: '[Link]',
styleUrls: ['[Link]']
})
export class AppComponent {
result;
constructor(obj: HttpClient) {
[Link]('[Link]
.subscribe((response) => {
[Link](response);
[Link] = response;
});
}
}
[Link]('[Link]
{ observe: 'response' }).subscribe(
(res)=>{
[Link](res)
}
)
@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;
});
}
}
@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[];
getEmployees(): Observable<Employee[]> {
return [Link]<Employee[]>([Link], { observe: 'body' }).pipe(
map((response: Employee[]) => {
return [Link]((emp: Employee) => {
return new Employee([Link], [Link], [Link], [Link]);
});
})
);
}
return next(req).pipe(
finalize(() => [Link]()),
);
}
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'),
});
// createObservable3 = interval(2000);
//testObservable3 = [Link](val => [Link](val));
createObservable4 = interval(2000);
createObservable4_take = [Link](take(5));
testObservable4 = this.createObservable4_take.subscribe(val => [Link](val));
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 }))
);
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 {
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 {
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));
}
@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>
ngAfterViewInit() {
fromEvent([Link], 'click').pipe(exhaustMap((val) => {
return [Link]('[Link]
})).subscribe({
next: (res) => [Link]('Response:', res),
error: (err) => [Link]('Error:', err),
})
}
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]);
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;
@Component({
selector: 'app-rxjs2',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class Rxjs2Component implements OnInit {
newMsg
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>
[Link]
---------------------
import { Component, OnInit } from '@angular/core';
import { TodoService } from '../[Link]';
@Component({
selector: 'app-todo-add',
template: `
<div>
<h3>Add Todo</h3>
<input #addToDo />
<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);
}
}
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);
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);
}
<style>
[Link]-invalid{
border:5px solid red;
}
[Link]-valid{
border:5px solid green;
}
</style>
<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>
<h3>{{[Link] | json}}</h3>
<h3>{{[Link]}}</h3>
<div>{{[Link] | json}}</div>
<div>{{[Link] | json}}</div>
<div></div>
</form>
<hr>
<div> Form Value: {{ [Link] | json }}</div>
<div> Form Valid Status: {{ [Link] | json }} </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 };
}
<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 {
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>
</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);
}
newSkill(): FormGroup {
return [Link]({skill: '',exp: ''});
}
addEmployeeSkill(empIndex: number) {
[Link](empIndex).push([Link]());
}
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>
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)
);
}
}
<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>
<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;
generatePassword() {
const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const lower = 'abcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
if (!validChars) {
[Link] = '⚠️ Select at least one option';
return;
}
[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';
@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]';
{
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>
{
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
}
};
===============
<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;
}
@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;
}
}
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]();
});
beforeEach(async () => {
await [Link]({
imports: [UserListComponent],
providers: [
provideHttpClient(),
UserService
]
})
.compileComponents();
fixture = [Link](UserListComponent);
component = [Link];
[Link]();
userService = [Link](UserService)
});
beforeEach(function () {
weatherService = new WeatherService();
weatherProcessor = new WeatherProcessor(weatherService);
});
// Verify results
expect([Link]).toHaveBeenCalledWith("New York");
expect(result).toBe(true); // 35 > 30, so it's hot
});
// Verify results
expect([Link]).toHaveBeenCalledWith("London");
expect(result).toBe(false); // 20 < 30, so it's not hot
});
[Link]("Paris");
[Link]("Berlin");
6. [Link]
<h2>Count value is : {{count$ | async}}</h2>
<button (click)="increment()">Increment</button>
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]}} {{[Link]}}
</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>
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])
});
}
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];
}
}
@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);
}
}