Skip to main content

Angular 17 if else Statement Example | @if @else block conditionals

B Built-in control flow and the NgIf, NgSwitch and NgFor structural directives:

1.     The @if block replaces *ngIf for expressing conditional parts of the UI.

2.     The @switch block replaces ngSwitch with major benefits.

3.     The @for block replaces *ngFor for iteration, and has several differences compared to its structural directive NgFor predecessor.

4.     The track setting replaces NgFor's concept of a trackBy function.

New Control Flow in Templates - new @if, @switch, @for, @case, @empty @end control flow syntax:

Before Angular 17: Let’s look at a one-by-one comparison with *ngIf:

<div *ngIf="loggedIn; else guestUser">

  The user is logged in to the application

</div>

<ng-template #guestUser>

  The user is not logged in to the application

</ng-template>


From Angular 17: The built-in if-else statements, this @if @else blocks conditionals looks like:

The @if block conditionally displays its content when its condition expression is true.

Let's see the example, here ‘a’ and ‘b’ are two of the variables that are used in the conditionals @if block.

@if (a > b) {

   {{a}} is greater than {{b}}

}

The @if block might have one or more associated @else blocks. Immediately after an @if block, you can optionally specify any number of @else if blocks and one @else block:

@if (a > b) {

  {{a}} is greater than {{b}

} @else if (b > a) {

  {{a}} is less than {{b}}

} @else {

  {{a}} is equal to {{b}}

}


Referencing the conditional expression's result:

@if (users$ | async; as users) {

  {{ users.length }}

}


See another example,

@if (loggedIn) {

  The user is logged in to the application

} @else {

  The user is not logged in to the application

}