Explain *ngIf,*ngFor, and *ngSwitch directives

Beginner

Answer

*ngIf: Conditionally includes or excludes an element from the DOM:

<div *ngIf="isVisible">This will show conditionally</div>
<div *ngIf="user; else noUser">Welcome {{user.name}}</div>
<ng-template #noUser>Please log in</ng-template>

*ngFor: Repeats an element for each item in a collection:

<li *ngFor="let item of items; index as i; trackBy: trackByFn">
  {{i}}: {{item.name}}
</li>

*ngSwitch: Conditionally displays one element from several possibilities:

<div [ngSwitch]="condition">
  <p *ngSwitchCase="'A'">Case A</p>
  <p *ngSwitchCase="'B'">Case B</p>
  <p *ngSwitchDefault>Default case</p>
</div>