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>

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

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.

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

1️⃣ When is this useful?

  • Access deep properties in an object
<span
  *ngIf="settings.data?.details?.groupName as groupName"
  >{{ groupName }}
</span>
  • The condition includes pipe, and you don’t want to apply the pipe again
<span
  *ngIf="settings.data.details.groupName | someHelperPipe:'accountNumber' as accountNumber"
  >{{ accountNumber }}
</span>
  • The condition includes a function call, and you don’t want to call it again. Obviously you don’t want to use a function call in the template, but sometimes you are lazy and just use it anyway 😂

Read this article to find out Why you should never use function calls in Angular template expressions

<span
  *ngIf="generateAccountNumber(settings.data.details.groupName) as accountNumber"
  >{{ accountNumber }}
</span>

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">
  <div></div>
</ng-template>

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

@Input()
set ngIf(condition: T) {
  this._context.$implicit = this._context.ngIf = condition;
  this._updateView();
}

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