Directives & Pipes
Structural Directives Deep Dive
*ngIf, *ngFor Internals
💡 Structural directives ek construction crew jaisa hai jo actually DOM ki "structure" badalta hai — elements add/remove karna, jaise deewarein banana/todna, sirf paint (styling) change karna nahi.
Structural directives (* prefix wale) DOM STRUCTURE ko modify karte hain — elements add, remove, ya repeat karte hain. Underneath, * syntax ek "syntactic sugar" hai — *ngIf="condition" actually <ng-template [ngIf]="condition"> mein "desugar" hota hai. Sirf EK structural directive per element allowed hai (do * combine nahi ho sakte).
// *ngFor with index, trackBy:
// <li *ngFor="let item of items; let i = index; trackBy: trackByFn">
// {{ i }}: {{ item.name }}
// </li>
// Component:
export class ListComponent {
items = [{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }];
trackByFn(index: number, item: any) {
return item.id; // Angular ab items ko ID se track karta hai, index se nahi
}
}
// Desugared form (*ngIf underneath actually ye hai):
// <ng-template [ngIf]="condition">
// <p>Content</p>
// </ng-template>🏗️
Structural directives ek construction crew jaisa hai jo actually DOM ki "structure" badalta hai — elements add/remove karna, jaise deewarein banana/todna, sirf paint (styling) change karna nahi.
1 / 6
⚡ झट से Recap
- * prefix = structural directive, DOM structure modify karta hai
- Underneath <ng-template> mein "desugar" hota hai
- trackBy = performance optimization, *ngFor list rendering ke liye zaroori
इस page में (2 subtopics)
Angular 17+ ek NAYA control flow syntax laaya — @if, @for, @switch — jo *ngIf/*ngFor ko REPLACE karne ka intent rakhta hai, built-in template syntax ke roop mein (koi directive import nahi chahiye), aur better performance.
<!-- Modern syntax (Angular 17+): -->
@if (isLoggedIn) {
<p>Welcome back!</p>
} @else {
<p>Please log in</p>
}
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
} @empty {
<li>No items found</li>
}Tip: Naye syntax mein trackBy MANDATORY hai @for ke saath (track item.id likhna zaroori hai) — Angular team ne jaan-boojh kar isse enforce kiya, kyunki purane *ngFor mein trackBy bhoolna itna common performance bug tha.
Ek element par DO structural directives (jaise *ngIf AUR *ngFor) directly nahi laga sakte — ng-container use karके, unhe nested karna padta hai.
<!-- GALAT — do structural directives ek element par: -->
<!-- <li *ngFor="let item of items" *ngIf="item.visible">{{item.name}}</li> -->
<!-- SAHI — ng-container se nest karo: -->
<ng-container *ngFor="let item of items">
<li *ngIf="item.visible">{{ item.name }}</li>
</ng-container>Common Mistake: Do structural directives ek element par lagाने ki koshish COMPILE ERROR deती hai — "can't have multiple template bindings on one element". ng-container ek clean workaround hai, extra DOM element bhi nahi add karta.