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?
Use the async pipe with ngIfWe can also use it with the ngIf or ngFor etc. The following example shows how NOT to use the observable with ngIf directive. The condition (obsValue | async) becomes true , when the observable returns a value.
In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element. The above code returns following error.
Async pipe creationOn the first call to transform, a subscription will be created from the observable we passed in. If our observable emits a new value, the display value ( this. _latestValue ) will be updated. Note, obj is the observable we've passed in, also known as the source observable.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With