Directives — First Look
Directives Angular ke special HTML attributes hain jo elements ka BEHAVIOR badalte hain. *ngIf conditionally element ko render karta hai (DOM mein add/remove). *ngFor ek array ke har item ke liye element ko REPEAT karta hai. * prefix batata hai ye "structural directive" hai (DOM structure change karta hai) — detail Directives & Pipes category mein aayega.
// *ngIf — conditional rendering:
// <p *ngIf="isLoggedIn">Welcome back!</p>
// <p *ngIf="!isLoggedIn">Please log in</p>
// *ngFor — list rendering:
// <ul>
// <li *ngFor="let fruit of fruits">{{ fruit }}</li>
// </ul>
// Component:
export class ListComponent {
isLoggedIn = true;
fruits = ['Apple', 'Banana', 'Cherry'];
}- *ngIf = conditional rendering, DOM se add/remove karta hai
- *ngFor = array ke har item ke liye element repeat karta hai
- * prefix = "structural directive" ka signal
*ngIf/else sirf do options ke liye theek hai. *ngSwitch (switch statement jaisa) MULTIPLE conditions ke beech choose karne ke liye better hai, jab 3+ possible states hon.
// <div [ngSwitch]="userRole">
// <p *ngSwitchCase="'admin'">Admin Dashboard</p>
// <p *ngSwitchCase="'editor'">Editor Panel</p>
// <p *ngSwitchDefault>Guest View</p>
// </div>ng-container ek "invisible wrapper" hai — grouping ke liye, bina extra DOM element add kiye. ng-template kuch content define karta hai jo NORMALLY render nahi hota, sirf explicitly reference kiye jaane par (jaise *ngIf ke "else" part mein).
// ng-container — extra div/span nahi chahiye:
// <ng-container *ngIf="isLoggedIn">
// <h1>Welcome</h1>
// <p>Dashboard content</p>
// </ng-container>
// ng-template — *ngIf ke saath "else":
// <p *ngIf="isLoggedIn; else loginPrompt">Welcome!</p>
// <ng-template #loginPrompt>
// <p>Please log in</p>
// </ng-template>