🎛️
Basics

Directives — First Look

*ngIf, *ngFor Preview
💡 Directives HTML ko "extra powers" dete hain — jaise ek normal instruction ko conditional bana dena ("agar ye true hai, tabhi dikhao") ya repeating bana dena ("har item ke liye ye repeat karo").

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'];
}
🎛️
Directives HTML ko "extra powers" dete hain — jaise ek normal instruction ko conditional bana dena ("agar ye true hai, tabhi dikhao") ya repeating bana dena ("har item ke liye ye repeat karo").
1 / 2
⚡ झट से Recap
  • *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
इस page में (2 subtopics)

*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>
💡Tip: *ngSwitch especially useful hai jab EK hi variable ki multiple possible values ke against different UI dikhाना ho — nested *ngIf/*ngIf-else chains se zyada readable.

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>
💡Tip: ng-container tab useful hai jab tumhe conditional/loop logic chahiye ho, lekin koi extra wrapping element (div) DOM mein nahi chahiye (jaise styling/layout break na ho).