1

I find myself in this situation quite often when I'd like to do the following:

<component-name 
  *ngIf="(referralsService.referrals$ | async; let referrals).length > 0
></component-name>

But this is not allowed. Is there a better way to accomplish allowing me to name my variable so I can use it later while also calling length or something else on it?

1 Answer 1

3

There is no way to do this in one *ngIf statement, but you can use the <ng-container> wrapper:

<ng-container *ngIf="referralsService.referrals$ | async as referrals">
  <component-name *ngIf="referrals.length > 0"></component-name>
</ng-container>

The Angular <ng-container> tag is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

For two observables you can use:

<ng-container *ngIf="{ 
  unused: (referralsService.unusedReferrals$ | async),
  used: ( referralsService.referrals$ | async) 
} as referrals">
  <component-name-1 *ngIf="referrals.used?.length > 0"></component-name-1>
  <component-name-2 *ngIf="referrals.unused?.length > 0"></component-name-2>
</ng-container>
Sign up to request clarification or add additional context in comments.

3 Comments

What if I had 2 async pipes? <ng-container *ngIf="referralsService.referrals$ | async as referrals && referralsService.unusedReferrals$ | async as unusedReferrals"> doesn't seem to work
nope, you need to wrap that in another <ng-container> or use the object approach, but you'll lose some template code hinting
@JeremyThomas I've updated my answer if you need to use two observables. I personally am not a big fan of it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.