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>
<span
*ngIf="settings.data?.details?.groupName as groupName"
>{{ groupName }}
</span>
<span
*ngIf="settings.data.details.groupName | someHelperPipe:'accountNumber' as accountNumber"
>{{ accountNumber }}
</span>
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>
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();
}
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.