Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting two async subscriptions in one Angular *ngIf statement

Tags:

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?

like image 834
Sammy Avatar asked Jun 30 '17 22:06

Sammy


People also ask

Can we use async in ngIf?

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.

Can we have two ngIf in angular?

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.

Does Async pipe create a new subscription?

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.

Does Async pipe subscribe?

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.


2 Answers

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

  • How to declare a variable in a template in Angular2
like image 65
yurzui Avatar answered Sep 18 '22 13:09

yurzui


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> 
like image 39
kayjtea Avatar answered Sep 19 '22 13:09

kayjtea