Member-only story

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>