Member-only story

ngIf — Store the conditional result in a variable

Trung Vo
2 min readJan 15, 2024

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 author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Trung Vo
Trung Vo

Written by Trung Vo

A seasoned front-end engineer with 9 years of passion in creating experience-driven products. I am proficient in Angular, React and TypeScript development.

No responses yet

Write a response

Ahah Trung Vo you’re so right! Many thanks for reporting these mistakes I will fix them! Since, I’m working with Vue.js I guess I’ve forgotten my Angular basics…