MyInternships.in

Directives, Pipes & Templates

Angular Control Flow if for switch

Angular 17 introduced built-in template control flow — @if, @for, @switch and @defer — as a replacement for the *ngIf and *ngFor directives. It reads more like ordinary code, needs no imports, and is faster at runtime.


What is Control Flow if for switch in Angular?

Angular 17 introduced built-in template control flow — @if, @for, @switch and @defer — as a replacement for the *ngIf and *ngFor directives. It reads more like ordinary code, needs no imports, and is faster at runtime.

Why Control Flow if for switch matters

The new syntax removes the CommonModule import that trips up every standalone beginner, makes trackBy mandatory (so the common performance bug cannot happen), and adds an @empty block for the empty-list case.

Control Flow if for switch example

The new control flow blocks
HTML
@if (jobs.length > 0) {
  @for (job of jobs; track job.id) {
    <app-job-card [job]="job" />
  } @empty {
    <p>No internships found.</p>
  }
} @else if (loading) {
  <app-spinner />
} @else {
  <p>Something went wrong.</p>
}

@switch (status) {
  @case ('open')   { <span class="tag">Accepting applications</span> }
  @case ('closed') { <span class="tag muted">Closed</span> }
  @default         { <span class="tag">Unknown</span> }
}

Key points to remember

  • track is required in @for — the framework will not let you skip it.
  • @empty handles the zero-items case without a separate @if.
  • ng generate @angular/core:control-flow migrates an existing project automatically.
  • The old directives still work; migration can be gradual.

Old syntax to new

BeforeNow
*ngIf="cond"@if (cond) { … }
*ngIf="cond; else tpl"@if (cond) { … } @else { … }
*ngFor="let x of xs; trackBy: fn"@for (x of xs; track x.id) { … }
[ngSwitch] / *ngSwitchCase@switch / @case
manual lazy loading@defer (on viewport) { … }

Angular Control Flow if for switch— Interview Questions & FAQs

Should I use @if or *ngIf in new Angular code?+

Use @if. It is the recommended syntax from Angular 17 onward, requires no CommonModule import, and compiles to more efficient code. The old directives remain supported for existing projects.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships