23
votes

I have the following in my component template:

<div *ngIf="user$ | async as user>...</div>

Within the above div I would like to use the async pipe to subscribe to another observable only once, and use it just like user above throughout the template. So for instance, would something like this be possible:

<ng-template *ngIf="language$ | async as language>
<div *ngIf=" user$ | async as user>
  <p>All template code that would use both {{user}} and {{language}} would go in between</p>
  </div>
</ng-template>

Or can this even be combined in one statement?

3
I think you're asking if you can introduce "user" as a new template variable, and the answer is no. The async pipe just yields the value as part of the expression. You would have to use the async pipe everywhere in the template you want to use the user value.Reactgular
All the logic I need is within the div above. I therefore do not need to reintroduce user as a variable anywhere else, since I already have it.Sammy
Please add more code that will explain what you are trying to doyurzui
Right, my only issue here is that I'm using an *ngIf for a value that I know for a fact exists, which is in this case the language observable.Sammy

3 Answers

21
votes

You can use object as variable:

<div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
    <b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
</div>

Plunker Example

See also

12
votes

The problem with using "object as variable" is that it doesn't have the same behavior as the code in the question (plus it's a mild abuse of *ngIf to have it always evaluate to true). To get the desired behavior you need:

<div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
   <ng-container *ngIf="userLanguage.language && userLanguage.user"> 
      <b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
   </ng-container>
</div>
3
votes

While the other solutions work, they slightly abuse the purpose of ngIf which should only optionally render a template. I've written an ngxInit directive that always renders even if the expression result is "falsy".

<div *ngxInit="{ language: language$ | async, user: user$ | async } as userLanguage">
   <!-- content -->
</div>

see https://github.com/amitport/ngx-init