Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular @if vs ngIf, are they different?

Tags:

angular

Is there any benefit of using the new @if instead of the classic ngIf directive?

*ngIf version:

@Component({
  standalone: true,
  selector: 'scrollbars',
  imports: [NgIf, ScrollbarX, ScrollbarY],
  template: `
    <scrollbar-x *ngIf="horizontalUsed()"/>
    <scrollbar-y *ngIf="verticalUsed()"/>
  `
})

@if version:

@Component({
  standalone: true,
  selector: 'scrollbars',
  imports: [ScrollbarX, ScrollbarY],
  template: `
    @if (verticalUsed()) {
      <scrollbar-y/>
    }
    @if (horizontalUsed()) {
      <scrollbar-x/>
    }
  `
})

Besides the syntax difference, I noticed that I don't need to import NgIf or CommonModule to make @if work, which is nice!

I would appreciate if someone can explain if it works differently behind the scene

like image 603
Murhaf Sousli Avatar asked Dec 07 '25 06:12

Murhaf Sousli


2 Answers

Functionnaly speaking yes, An @if block replaces the usage of the ngIf directive.

However, there are some technical advantages to use the new control flow blocks (@for/@if/@switch).

  1. You don't need to import the directive or the CommonModule when build standalone components.
  2. Droping thoses directives also drops a few kBs from the main bundle.
  3. Expect some perf improvements (due to less template instructions needed), some details in this article
like image 86
Matthieu Riegler Avatar answered Dec 09 '25 00:12

Matthieu Riegler


@if vs *nglf

  • less verbose, more intuitive
  • no need for imports (It comes with SharedModule)
  • supports else if and else conditions

Additional Tips: @for vs *ngFor

  • less verbose, more intuitive
  • The @for now forces developers to use a tracking function, so performance-wise it's safer
  • The @for syntax is automatically included in templates, no explicit imports are needed.

Migrate to the new control flow syntax

Run this command to upgrade your projects: ng generate @angular/core:control-flow

Need More visit angular official doc

like image 26
Srikrushna Avatar answered Dec 09 '25 00:12

Srikrushna