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?
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:
While the other solutions work, they slightly abuse the purpose of
ngIf
which should only optionally render a template. I've written anngxInit
directive that always renders even if the expression result is "falsy".see https://github.com/amitport/ngx-init
You can use object as variable:
Plunker Example
See also