Angular 15: Essential Guide and Examples
Angular 15: Essential Guide and Examples
-----------------------
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:[] 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: './[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>
@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 [[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-14: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];
}
}
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() {
[Link] = [
{ 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() {
[Link] = [
{ 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 [Link];
}
}
************************
<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>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</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('[Link]-color') myBgColor: string = '';
@HostListener('keyup', ['$event'])
handleKeyPress(e: { target: { 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('click', ['$[Link]'])
onClick(btn: any) {
[Link]('button', btn, 'number of clicks:', [Link]++);
}
}
<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 = [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)
}
}
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){
[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);
}
}
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-34 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]();
}
}
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>
@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-37 @viewChildren
-----------------------
@ViewChildren('myInputBox') allinputBoxes: any;
ngAfterViewInit() {
[Link]([Link]);
[Link]._results?.forEach((ele: any) => {
[Link] = 'green';
});
}
@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;
});
}
}
@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]);
});
})
);
}
============
{ 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: '[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: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 = [Link](
'[Link]
);
let request2 = [Link](
'[Link]
);
let request3 = [Link](
'[Link]
);
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: './[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()
usersPublisher = of(1, 2, 3, 4);
usersSubscriber2 = [Link](
mergeMap((user) => {
const url =`[Link]
return [Link](url); //inner observable
})
).subscribe((userData) => {
[Link](userData);
});
@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));
}
interface PeopleData {
name: string;
birthYear: string;
height: number;
weight: number;
eyeColor: string;
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements OnInit {
searchResult$: Observable<PeopleData>;
ngOnInit() {
[Link]$ = [Link](
switchMap((term) =>
[Link]<any>(`[Link]
),
map((response) =>
[Link] > 0 ? [Link][0] : { name: 'No results' }
),
map(
(response) =>
({
name: [Link],
birthYear: response.birth_year,
height: Number([Link]),
weight: Number([Link]),
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>
{{ [Link] }}
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Height
</td>
<td>
{{ [Link] }} cm
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Weight
</td>
<td>
{{ [Link] }} kg
</td>
</tr>
<tr></tr>
<tr>
<td class="heading">
Eye Color
</td>
<td>
{{ [Link] }}
</td>
</tr>
<tr></tr>
</table>
<ng-template #noResults>
No Results Found
</ng-template>
</ng-container>
</div>
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 {}
addToDo(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<Todo[]> | undefined;
constructor(private todoService: TodoService) {}
ngOnInit(): void {
[Link] = [Link];
}
deleteTodo(id: number) {
[Link](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>
[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>
</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]}`);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
empForm!: FormGroup;
ngOnInit() {
[Link] = [Link]({
employees: [Link]([])
});
}
employees(): FormArray {
return [Link]('employees') as FormArray;
}
newEmployee(): 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 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>
{{[Link] | json}}
program-61: 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>
Program-62:Path-Param Example
-----------------------------
1. create productDetailsComponent
ng g c productDetails
canActivate() {
if ([Link] == '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: './[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;
}
}
2. Create Folders & Files manually for store , actions, reducers and components
store-->[Link]
actions-->[Link]
reducers-->[Link]
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 ([Link]) {
case 'ADD_TODO': {
const newToDo = {
id: [Link] + 1,
text: [Link],
isCompleted: false,
};
return [...state, newToDo];
}
case 'TOGGLE_TODO': {
return [Link]((todo) => {
return [Link] !== [Link]
? todo
: [Link]({}, todo, { isCompleted: ![Link] });
});
}
case 'DELETE_TODO': {
return [Link]((todo) => {
return [Link] !== [Link];
});
}
default: {
return state;
}
}
}
export const rootReducer = {
todosReducer
};
7. todo-list [Link]
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { deleteTodo, toggleToDo } from '../actions/actions';
@Component({
selector: 'app-todolist',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class TodolistComponent implements OnInit {
allToDos: any;
constructor(private store: Store) {}
ngOnInit(): void {
[Link]((state: any) => {
[Link]('state', state);
[Link] = [Link];
});
}
deleteMyTodo(id: number) {
const actionObj = deleteTodo(id);
[Link](actionObj);
}
toggleMyTodo(id: number) {
const actionObj = toggleToDo(id);
[Link](actionObj);
}
}
8. [Link]
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { addTodo } from '../actions/actions';
@Component({
selector: 'app-add-todo',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AddTodoComponent implements OnInit {
constructor(private store: Store) {}
ngOnInit(): void {}
addNewTodo(text: string) {
const actionObj = addTodo(text); // action creator
[Link](actionObj);
}
}