Wanna see something cool? Check out Angular Spotify 🎧

ngIf - Store the conditional result in a variable

ngIf - Storing a conditional result in a variable

Sometimes we need to do an *ngIf with a complex condition, and we render the same result into the UI. For instance:

<div *ngIf="somethingThatCanBeVeryLong">{{ somethingThatCanBeVeryLong }}</div>

  *ngIf="settings.data.details.groupName | someHelperPipe:'accountNumber'"
  >{{ settings.data.details.groupName | someHelperPipe:'accountNumber' }}

In this case, we can use the as keyword to store the condition as a local variable and use it in the template. We are probably familiar with this syntax in async pipe *ngIf="users$ | async as users", but we can use it in any other case with ngIf.

  *ngIf="settings.data.details.groupName | someHelperPipe:'accountNumber' as accountNumber"
  >{{ accountNumber }}

1️⃣ When is this useful?

  • Access deep properties in an object
  *ngIf="settings.data?.details?.groupName as groupName"
  >{{ groupName }}
  • The condition includes pipe, and you don’t want to apply the pipe again
  *ngIf="settings.data.details.groupName | someHelperPipe:'accountNumber' as accountNumber"
  >{{ accountNumber }}
  *ngIf="generateAccountNumber(settings.data.details.groupName) as accountNumber"
  >{{ accountNumber }}

2️⃣ How does it work under the hood?

Yeah, it’s magic that happens during template compilation.

The template below

<div *ngIf="user$ | async as user"></div>

is just sugar for:

<ng-template [ngIf]="user$ | async" let-user="ngIf">

On Angular source code, it sets the context to the same condition input -> common/src/directives/ng_if.ts#L171

set ngIf(condition: T) {
  this._context.$implicit = this._context.ngIf = condition;

3️⃣ How as works?

In short, the compiler sees as keyword and do some magic so that it is equivalent to the let syntax.

See this yurzui’s stackoverflow.com answer for more details.

Read more on *ngIf - Storing a conditional result in a variable.

Published 31 Aug 2022

    Read more

     — Common use cases and solutions for accessibility in Angular
     — Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)
     — /usr/local/bin/code: line 6: python: command not found
     — Multiple ng-content
     — My React Reading List

    Follow @trungvose on Twitter for more!