Angular 15 Programs
Angular 15 Programs
-----------------------
1. npm install bootstrap
2. add the below line in 'styles.css'
@import '~bootstrap/dist/css/bootstrap.css'
3. add "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js" in angular.json
projects ->architect->build->scripts:[] array
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")
}
}
<head>
<meta charset="utf-8">
<title>MyProject1</title>
<base href="/">
@Component({
selector: 'my-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('name') nameRef;
@ViewChild('age') ageRef;
myName;
myAge;
showData() {
this.myName = this.nameRef.nativeElement.value;
this.myAge = this.ageRef.nativeElement.value;
alert(`${this.myName} ${this.myAge}`)
}
}
*******************
<h1>Using Template Reference variable in component file</h1>
@Component({
selector: 'app-root',
template: `
<div *ngIf="x%2 == 0; else odd">
{{x}} is an even number
</div>
<ng-template #odd>
{{x}} is an odd number
</ng-template>
`
})
export class AppComponent {
x: number = 6;
}
----------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;
}
@Component({
selector: 'my-app',
styles:['.myClass{color:red;border:5px solid green;}'],
template: `
<h1>
<p [class.myClass]='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 this.myClasses;
}
}
program-14:style binding
------------------------
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>
<p [style.color]="num % 2 == 0 ? 'blue' : 'red'"> Add a style </p>
<p [style.fontSize.px]='48'> Add style with unit </p>
<p [style.background-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 this.myStyles;
}
}
employees = [
{ eId: 101, name: 'sanjay', sal: 5000, gender: 'male' },
{ eId: 104, name: 'geeta', sal: 8000, gender: 'female' },
{ eId: 103, name: 'ranjan', sal: 7000, gender: 'female' },
{ eId: 102, name: 'sita', sal: 9000, gender: 'male' },
];
students:any[] = []
constructor() {
this.employees = [
{ eId: 101, name: "sanjay", sal: 5000 },
{ eId: 104, name: "deepak", sal: 8000 },
{ eId: 103, name: "ranjan", sal: 7000 },
{ eId: 102, name: "manoj", sal: 9000 }
]
}
getNewEmployees() {
this.employees = [
{ eId: 101, name: "sanjay", sal: 5000 },
{ eId: 104, name: "deepak", sal: 8000 },
{ eId: 103, name: "ranjan", sal: 7000 },
{ eId: 102, name: "manoj", sal: 9000 },
{ eId: 106, name: "rajeev", sal: 9000 }
]
}
trackByEmpId(employee: any) {
return employee.eId;
}
}
************************
<table border=5 align=center width=50%>
<tr>
<th>EmpId</th>
<th>name</th>
<th>salary</th>
</tr>
<tr *ngFor="let emp of employees;trackBy:trackByEmpId">
<td>{{emp.eId}}</td>
<td>{{emp.name}}</td>
<td>{{emp.sal}}</td>
</tr>
</table>
<button (click)="getNewEmployees()">Refresh Data</button>
Program-17 : Pagination
----------------------
1. Install Pagination Library
npm i ngx-pagination
@Directive({
selector: '[numberonly]'
})
export class NumberonlyDirective {
@HostBinding('style.background-color') myBgColor: string = '';
@HostListener('keyup', ['$event'])
handleKeyPress(e: { target: { value: string } }) {
let regex = new RegExp(/^[0-9]*$/);
if (!regex.test(e.target.value)) {
this.myBgColor = 'red';
} else {
this.myBgColor = 'cyan';
}
}
}
******************
<input type="text" numberonly name="salary" id="salary">
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
@HostListener('click')
clickHandler(e) {
this.location.back();
}
}
@HostListener('click', ['$event.target'])
onClick(btn: any) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}
<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>
format '3.2-5'
***************
minIntegerDigits = 3
minFractionDigits = 2
maxFractionDigits = 5
searchText = searchText.toLowerCase();
return items.filter(item => {
return JSON.stringify(item).toLowerCase().includes(searchText);
});
}
}
@Component({
selector: 'my-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [CurrencyPipe]
})
export class AppComponent {
constructor(private currencyPipe: CurrencyPipe) {
}
sal = 5000;
formattedSal1 = this.currencyPipe.transform(this.sal);
formattedSal2 = this.currencyPipe.transform(this.sal, '$');
}
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) {
this.originalList.push(newDigit)
this.pureSortableDigits.push(newDigit)
this.impureSortableDigits.push(newDigit)
}
}
program-32: 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>
<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){
this.aParent = temp;
}
getB(temp:string){
this.bParent = 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{
this.aEvent.emit(this.a);
}
sendB():void{
this.bEvent.emit(this.b);
}
}
constructor() {
console.log("Parent constructor")
}
ngOnInit() {
console.log('Parent ngOnInit');
}
ngOnChanges() {
console.log('Parent ngOnChanges');
}
ngDoCheck() {
console.log('Parent ngDoCheck');
}
ngAfterContentInit() {
console.log('Parent ngAfterContentInit');
}
ngAfterContentChecked() {
console.log('Parent ngAfterContentChecked')
}
ngAfterViewInit() {
console.log('Parent ngAfterViewInit');
}
ngAfterViewChecked() {
console.log('Parent ngAfterViewChecked');
}
ngOnDestroy() {
console.log('Parent ngOnDestory');
}
increment() {
this.num++;
}
}
------
<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: './mychild.component.html',
styleUrls: ['./mychild.component.css'],
inputs: ['childNum']
})
export class MychildComponent implements OnInit {
constructor() {
console.log('child constructor');
}
ngOnInit() {
console.log('child ngOnInit');
}
ngOnChanges() {
console.log('child ngOnChanges');
}
ngDoCheck() {
console.log('child ngDoCheck');
}
ngAfterContentInit() {
console.log('child ngAfterContentInit');
}
ngAfterContentChecked() {
console.log('child ngAfterContentChecked')
}
ngAfterViewInit() {
console.log('child ngAfterViewInit');
}
ngAfterViewChecked() {
console.log('child ngAfterViewChecked');
}
ngOnDestroy() {
console.log('child ngOnDestory');
}
}
--------
<p>
This is child component <br>
child component Num: {{childNum}}
</p>
program-34 ngDOCheck()
-----------------------
import { Component, OnInit, OnChanges, ChangeDetectionStrategy, DoCheck,
ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
inputs: ['xChild'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnChanges, OnInit, DoCheck {
constructor(private changeDetectorObj: ChangeDetectorRef) {
}
ngOnChanges(myChanges) {
console.log('onchanges called', myChanges)
}
ngOnInit() {
console.log('oninit called')
}
ngDoCheck() {
this.changeDetectorObj.markForCheck();
}
}
constructor() {
console.log(this.inputBox); //not yet available
}
ngAfterViewInit() {
this.inputBox.nativeElement.focus();
console.log(this.inputBox)
}
}
*************
<h1>@ViewChild to inject a reference to a DOM element</h1>
<input type="text" #myInputBox>
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) childRef;
constructor() {
console.log("inside constructor")
// console.log(this.childRef.a); //not yet available
// console.log(this.childRef.b); //not yet available
}
ngAfterViewInit() {
console.log("inside ngAfterViewInit")
console.log(this.childRef.a);
console.log(this.childRef.b);
}
Program-37 @viewChildren
-----------------------
@ViewChildren('myInputBox') allinputBoxes: any;
ngAfterViewInit() {
console.log(this.allinputBoxes);
this.allinputBoxes._results?.forEach((ele: any) => {
ele.nativeElement.style.backgroundColor = 'green';
});
}
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
addResult;
subResult;
mulResult;
divResult;
constructor(obj : MathService){
let a = parseInt(prompt("enter a value"));
let b = parseInt(prompt("enter a value"));
this.addResult = obj.add(a,b);
this.subResult = obj.sub(a,b);
this.mulResult = obj.mul(a,b);`
this.divResult = obj.div(a,b);
}
}
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
result;
constructor(obj: HttpClient) {
obj.get('https://jsonplaceholder.typicode.com/comments')
.subscribe((response) => {
console.log(response);
this.result = response;
});
}
}
this.http.get('https://jsonplaceholder.typicode.com/posts',
{ observe: 'response' }).subscribe(
(res)=>{
console.log(res)
}
)
@Injectable({
providedIn: 'root'
})
export class TodoService {
constructor(public httpObj: HttpClient) {
}
getAllTodos(): Observable<Todo[]> {
return this.httpObj.get<Todo[]>('https://jsonplaceholder.typicode.com/todos')
}
}
app.component.ts
-----------------
import { Component } from "@angular/core";
import { Todo } from './todo';
import { TodoService } from './todo.service'
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
todos: Todo[];
constructor(public todoServiceObj: TodoService) {
}
ngOnInit() {
this.todoServiceObj.getAllTodos()
.subscribe((response: Todo[]) => {
this.todos = response;
});
}
}
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
commentList: Comment[];
getEmployees(): Observable<Employee[]> {
return this.httpClient.get<Employee[]>(this.url, { observe: 'body' }).pipe(
map((response: Employee[]) => {
return response.map((emp: Employee) => {
return new Employee(emp.id, emp.firstName, emp.lastName, emp.sal);
});
})
);
}
============
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor1, multi: true }
//in modules providers
Program-47: 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: 'app.component.html'
})
export class AppComponent {
//Create an observable with given subscription function
createObservable1 = new Observable(function (observer) {
observer.next("aaaaaa");
observer.next("bbbbbb");
observer.next("cccccc");
});
subscriber1 = this.producer1.subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('completed'),
});
// createObservable3 = interval(2000);
//testObservable3 = this.createObservable3.subscribe(val => console.log(val));
createObservable4 = interval(2000);
createObservable4_take = this.createObservable4.pipe(take(5));
testObservable4 = this.createObservable4_take.subscribe(val => console.log(val));
Program:48 Zip()
--------------
zipDemo() {
let publisher1 = of(32, 31, 34);
let publisher2 = of('sanjay', 'ranjan', 'bishnu');
let publisher3 = of('bang', 'chennai', 'hyderabad');
let finalPublisher = zip(publisher1, publisher2, publisher3).pipe(
map(([age, name, add]) => ({ age, name, add }))
);
program-49 : forkjoin
----------------------
fetchDataFromMultipleAPIs() {
let request1 = this.httpClient.get(
'https://jsonplaceholder.typicode.com/todos'
);
let request2 = this.httpClient.get(
'https://jsonplaceholder.typicode.com/comments'
);
let request3 = this.httpClient.get(
'https://jsonplaceholder.typicode.com/users'
);
Program-50 : MergeMap
-----------------------
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements AfterViewInit {
constructor() {
this.clickObservable = new Observable();
}
ngAfterViewInit() {
this.clickObservable = fromEvent(this.button.nativeElement, 'click');
this.mergeMapExample();
}
innerObservable(count: number) {
return new Observable((observer) => {
setTimeout(() => { observer.next(count + " A") }, 1000);
setTimeout(() => { observer.next(count + " B") }, 2000);
setTimeout(() => { observer.next(count + " C") }, 3000);
setTimeout(() => { observer.next(count + " D") }, 4000);
setTimeout(() => { observer.next(count + " E"); observer.complete() }, 5000);
})
}
mergeMapExample() {
let obs =
this.clickObservable
.pipe(
mergeMap(() => {
this.count = this.count + 1;
return this.innerObservable(this.count)
})
)
.subscribe(val => console.log(val));
}
}
-----------------------------
// without mergeMap()
usersPublisher = of(1, 2, 3, 4);
usersSubscriber = this.usersPublisher.subscribe((user) => {
console.log(user);
const url = `https://jsonplaceholder.typicode.com/users/${user}`;
this.httpClient.get(url).subscribe((userData) => {
console.log(userData);
});
});
//with mergeMap()
usersPublisher = of(1, 2, 3, 4);
usersSubscriber2 = this.usersPublisher.pipe(
mergeMap((user) => {
const url =`https://jsonplaceholder.typicode.com/users/${user}`;
return this.httpClient.get(url); //inner observable
})
).subscribe((userData) => {
console.log(userData);
});
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements AfterViewInit {
constructor() {
this.clickObservable = new Observable();
}
ngAfterViewInit() {
this.clickObservable = fromEvent(this.button.nativeElement, 'click');
this.mergeMapExample();
}
innerObservable(count: number) {
return new Observable((observer) => {
setTimeout(() => { observer.next(count + " A") }, 1000);
setTimeout(() => { observer.next(count + " B") }, 2000);
setTimeout(() => { observer.next(count + " C") }, 3000);
setTimeout(() => { observer.next(count + " D") }, 4000);
setTimeout(() => { observer.next(count + " E"); observer.complete() }, 5000);
})
}
mergeMapExample() {
let obs =
this.clickObservable
.pipe(
concatMap(() => {
this.count = this.count + 1;
return this.innerObservable(this.count)
})
)
.subscribe(val => console.log(val));
}
interface PeopleData {
name: string;
birthYear: string;
height: number;
weight: number;
eyeColor: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
searchResult$: Observable<PeopleData>;
ngOnInit() {
this.searchResult$ = this.search.valueChanges.pipe(
switchMap((term) =>
this.http.get<any>(`https://swapi.dev/api/people/?search=${term}`)
),
map((response) =>
response.count > 0 ? response.results[0] : { name: 'No results' }
),
map(
(response) =>
({
name: response.name,
birthYear: response.birth_year,
height: Number(response.height),
weight: Number(response.mass),
eyeColor: response.eye_color,
} as PeopleData)
)
);
}
}
--------------------------------
<div class="body">
<h1>Search for a Star Wars Character</h1>
<p>
Simply start typing the name of your favorite Star Wars character to see
more details about them!
</p>
<div [formGroup]="searchFormGroup">
<input formControlName="search" />
</div>
<tr></tr>
<tr>
<td class="heading">
Birth Year
</td>
<td>
{{ person.birthYear }}
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Height
</td>
<td>
{{ person.height }} cm
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Weight
</td>
<td>
{{ person.weight }} kg
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Eye Color
</td>
<td>
{{ person.eyeColor }}
</td>
</tr>
<tr></tr>
</table>
<ng-template #noResults>
No Results Found
</ng-template>
</ng-container>
</div>
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next(null);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
--------
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../message.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-rxjs',
templateUrl: './rxjs.component.html',
styleUrls: ['./rxjs.component.css']
})
export class RxjsComponent implements OnInit {
messages: any[] = [];
subscription: Subscription;
@Component({
selector: 'app-rxjs2',
templateUrl: './rxjs2.component.html',
styleUrls: ['./rxjs2.component.css']
})
export class Rxjs2Component implements OnInit {
newMsg
sendMessage(): void {
// send message to subscribers via observable subject
this.messageService.sendMessage(this.newMsg);
}
clearMessages(): void {
// clear messages
this.messageService.clearMessages();
}
}
----------
<p>rxjs2 works!</p>
<input type="text" [(ngModel)]='newMsg'>
<button (click)='sendMessage()'>send message</button>
<button (click)='clearMessages()'>Clear Message</button>
todo-add.component.ts
---------------------
import { Component, OnInit } from '@angular/core';
import { TodoService } from '../todo.service';
@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 {}
addToDo(todoText: string) {
this.todoService.create({ id: 3, value: todoText });
}
}
todo-list.component.ts
----------------------
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Todo, TodoService } from '../todo.service';
@Component({
selector: 'app-todo-list',
template: `
<h3>Todo List</h3>
<div *ngFor="let todo of todos$ | async">
{{ todo.id }} {{ todo.value }}
<button (click)="deleteTodo(todo.id)">x</button>
</div>
`,
})
export class TodoListComponent implements OnInit {
todos: Observable<Todo[]> | undefined;
constructor(private todoService: TodoService) {}
ngOnInit(): void {
this.todos = this.todoService.todoObs;
}
deleteTodo(id: number) {
this.todoService.remove(id);
}
}
******
Angular Forms
*********
program-56: Form with Class Names
--------------------------------
<form name='myForm'>
Name:
<input name='uname' [(ngModel)]='name' required /><br><br>
Age:
<input name='uage' [(ngModel)]='age' />
</form>
<style>
input.ng-invalid{
border:5px solid red;
}
input.ng-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> {{ myForm.value | json }} </h2>
</form>
<hr>
<div> Form Value: {{ myForm.value | json }}</div>
<div> Form Valid Status: {{ myForm.status | json }} </div>
**********
import { Component} from '@angular/core';
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styles: [
'input.ng-invalid.ng-dirty{border:2px solid red}'
]
})
export class TemplateComponent {
submitMyForm(user: any) {
alert(`Name: ${user.name} Age: ${user.age}`);
}
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>{{registerForm.value | 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="address.hasError('required') && address.dirty"> Address is
Required </span>
<span *ngIf="address.hasError('minlength') && address.dirty"> Min 5
characters Required </span>
<span *ngIf="address.hasError('maxlength') && address.dirty"> max 10
characters allowed </span>
<br><br>
</form>
<hr>
<div> Form Value: {{myForm.value | json }} </div>
<div> Form Status:{{myForm.status | json }} </div>
</div>
***************
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
myFormBuilder;
myForm;
constructor() {
this.myFormBuilder = new FormBuilder();
this.generateForm();
}
get age() {
return this.myForm.get('age')
}
get address() {
return this.myForm.get('address')
}
generateForm() {
let formControlObj1 = new FormControl('sachin', [Validators.required,
Validators.pattern('[a-zA-z]+')]);
let formControlObj2 = new FormControl('35');
let formControlObj3 = new FormControl('mumbai', {
validators : [Validators.required,Validators.pattern('[a-zA-z]+')],
updateOn : 'blur'
});
this.myForm = this.myFormBuilder.group({
name: formControlObj1,
age: formControlObj2,
address: formControlObj3
})
}
submitMyForm() {
alert(`Name: ${this.myForm.value.name} Age: ${this.myForm.value.age} Address: $
{this.myForm.value.address}`);
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
empForm!: FormGroup;
ngOnInit() {
this.empForm = this.fb.group({
employees: this.fb.array([])
});
}
employees(): FormArray {
return this.empForm.get('employees') as FormArray;
}
newEmployee(): FormGroup {
return this.fb.group({
firstName: '',
lastName: '',
skills: this.fb.array([])
});
}
addEmployee() {
this.employees().push(this.newEmployee());
}
removeEmployee(empIndex: number) {
this.employees().removeAt(empIndex);
}
newSkill(): FormGroup {
return this.fb.group({
skill: '',
exp: ''
});
}
addEmployeeSkill(empIndex: number) {
this.employeeSkills(empIndex).push(this.newSkill());
}
onSubmit() {
console.log(this.empForm.value);
}
}
----------------------------------
<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 employees().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>
{{this.empForm.value | json}}
program-61: routing
--------------------
1. Specify the Base URL: <base href="/"> in index.html
2. Import RouterModule from '@angular/router'
3. Define the routes
app.module.ts
-------------
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, RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
routerconfig.ts
----------------
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { CareerComponent } from './career/career.component';
{
path: 'home',
component: HomeComponent
},
{
path: 'aboutUs',
component: AboutusComponent
},
{
path: 'career',
component: CareerComponent
},
{
path: '',
//redirectTo: 'home',
component:HomeComponent,
//pathMatch: 'full'
},
{
path: '**',
component: notFoundComponent
}
]
app.component.html
-------------------
<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>
Program-62:Path-Param Example
-----------------------------
1. create productDetailsComponent
ng g c productDetails
canActivate() {
if (this.userRole == 'admin') {
return true;
}
else {
alert("you are not allowed to visit this route");
return false;
}
}
}
----------------
{
path: 'product-details',
component: ProductDetailsComponent,
canActivate: [myGuard]
},
@Component({
selector: 'app-jasmine',
templateUrl: './jasmine.component.html',
styleUrls: ['./jasmine.component.css']
})
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;
}
}
2. Create Folders & Files manually for store , actions, reducers and components
store-->store.ts
actions-->actions.ts
reducers-->reducers.ts
components--> todoList , addTodo (ng g c todolist, ng g c addtodo)
const initialState = [
{ id: 1, text: 'ToDo 1', isCompleted: true },
{ id: 2, text: 'ToDo 2', isCompleted: false },
];
function todosReducer(state = initialState, action: any): any {
switch (action.type) {
case 'ADD_TODO': {
const newToDo = {
id: state.length + 1,
text: action.payload.text,
isCompleted: false,
};
return [...state, newToDo];
}
case 'TOGGLE_TODO': {
return state.map((todo) => {
return todo.id !== action.payload.id
? todo
: Object.assign({}, todo, { isCompleted: !todo.isCompleted });
});
}
case 'DELETE_TODO': {
return state.filter((todo) => {
return todo.id !== action.payload.id;
});
}
default: {
return state;
}
}
}
export const rootReducer = {
todosReducer
};
7. todo-list component.ts
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { deleteTodo, toggleToDo } from '../actions/actions';
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.css'],
})
export class TodolistComponent implements OnInit {
allToDos: any;
constructor(private store: Store) {}
ngOnInit(): void {
this.store.subscribe((state: any) => {
console.log('state', state);
this.allToDos = state.todosReducer;
});
}
deleteMyTodo(id: number) {
const actionObj = deleteTodo(id);
this.store.dispatch(actionObj);
}
toggleMyTodo(id: number) {
const actionObj = toggleToDo(id);
this.store.dispatch(actionObj);
}
}
8. add-todo.component.ts
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { addTodo } from '../actions/actions';
@Component({
selector: 'app-add-todo',
templateUrl: './add-todo.component.html',
styleUrls: ['./add-todo.component.css'],
})
export class AddTodoComponent implements OnInit {
constructor(private store: Store) {}
ngOnInit(): void {}
addNewTodo(text: string) {
const actionObj = addTodo(text); // action creator
this.store.dispatch(actionObj);
}
}