Directives Explained - NgFor, NgIf & NgSwitch with Examples
Previous
63
/
63
ngFor Directive
ngFor is used to apply looping in the template file (HTML).
It helps to repeat HTML elements using data from an array.
Template file means the HTML file of a component.
ngFor with Simple Array
TypeScript
students = ['Anil', 'Sam', 'Peter', 'Vinay', 'Bruce'];
HTML
<ul>
<li *ngFor="let x of students">
{{ x }}
</li>
</ul>
*ngForruns a loop on elementsxholds one value at a time- Interpolation
{{ }}is used to display data
Import for ngFor
ngFor must be imported to avoid errors.
import { NgFor } from '@angular/common';
@Component({
imports: [NgFor]
})
ngFor with Array of Objects
TypeScript
studentsData = [
{ name: 'Anil', age: 29, email: 'anil@test.com' },
{ name: 'Sam', age: 25, email: 'sam@test.com' },
{ name: 'Peter', age: 30, email: 'peter@test.com' }
];
HTML
<ul>
<li *ngFor="let student of studentsData">
{{ student.name }}, {{ student.age }}, {{ student.email }}
</li>
</ul>
- Used when array contains objects
- Access object values using dot (
.)
ngIf Directive
ngIf is used to show or hide elements based on condition.
Basic ngIf Example
TypeScript
show = false;
HTML
<h1 *ngIf="show">Heading</h1>
- Element shows only when condition is
true
Import for ngIf
import { NgIf } from '@angular/common';
@Component({
imports: [NgIf]
})
ngIf with Login / Logout Example
TypeScript
login = false;
HTML
<div *ngIf="login; else elseBlock">
<a>Logout</a>
</div>
<ng-template #elseBlock>
<a>Login</a>
</ng-template>
- If
loginis true → Logout shows - If false → Login shows
Multiple ngIf Conditions
TypeScript
block = 0;
HTML
<div *ngIf="block === 0">Heading Zero</div>
<div *ngIf="block === 1">Heading One</div>
<div *ngIf="block === 2">Heading Two</div>
Change Condition Using Button
HTML
<button (click)="updateBlock()">Update Block</button>
TypeScript
updateBlock() {
this.block++;
}
- Value changes on button click
- Different heading shows based on value
ngSwitch Directive
ngSwitch is used when there are many conditions.
It works similar to switch-case in programming.
Basic ngSwitch Example
TypeScript
color = 'red';
HTML
<div [ngSwitch]="color">
<h1 *ngSwitchCase="'red'">Red Color</h1>
<h1 *ngSwitchCase="'green'">Green Color</h1>
<h1 *ngSwitchCase="'blue'">Blue Color</h1>
<h1 *ngSwitchDefault>No Color Match</h1>
</div>
- Only one case runs at a time
- Default runs if no case matches
Import for ngSwitch
import { NgSwitch, NgSwitchCase, NgSwitchDefault } from '@angular/common';
@Component({
imports: [NgSwitch, NgSwitchCase, NgSwitchDefault]
})
ngSwitch with Button Click
HTML
<button (click)="changeColor('red')">Red</button>
<button (click)="changeColor('green')">Green</button>
<button (click)="changeColor('blue')">Blue</button>
TypeScript
changeColor(color: string) {
this.color = color;
}
- Button click updates value
- ngSwitch updates UI automatically