Search code examples
angular

Angular @if vs ngIf, are they different?


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


Solution

  • 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