Skip to content

@if(...)

Published on December 15, 2023

The new @if which we can use to replace *ngIf is available from Angular 17. The new syntax is much cleaner and easier to read and write, and more powerful.
Let’s go over the changes:

*ngIf -> @if

The old way of creating an if statement in your angular templates was by using the *ngIf directive.
The new way is by using the @if syntax.
let’s see an example:

import { Component, ChangeDetectionStrategy } from '@angular/core';
import {OldIfComponent} from './old-if.component';
import {NewIfComponent} from './new-if.component';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-root',
standalone: true,
imports: [OldIfComponent, NewIfComponent],
template: `
  <h1>*ngIf -> &#64;if</h1>
	<old-if></old-if>
	<new-if></new-if>
`,
})
export class AppComponent {	
}
Read-only

Few things to note here:

  • The @if syntax is much cleaner and readable.
  • The else case is much easier to write in the new syntax.
  • You can use @else if which you can’t in the old syntax.

Playground

You can practice the new @if syntax in the playground below:

import { Component, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
  <h1>Practice &#64;if</h1>		
`,
})
export class AppComponent {	
}