Ki2ito
Ki2ito

Reputation: 118

Correct syntax for NgIf using async pipe with multiple template variables?

With Angular, we can subscribe to an Observable and assign the result of the async pipe to another variable by doing :

    *ngIf="(data$ | async) as data; else loading"

We can check multiple conditions :

    *ngIf="(data1$ | async) && (data2$ | async); else loading"

But what is the correct syntax to verify multiple conditions using Angular "as" Keyword ?

I tried :

    *ngIf="((data1$ | async) as data1) && ((data2$ | async) as data2); else loading"

But I have an issue :

Parser Error: Unexpected token &&, expected identifier, keyword, or string

Upvotes: 9

Views: 4288

Answers (3)

Mike
Mike

Reputation: 41

Consider LppEdd answer.

combineLatest is not a correct use case, cause it will emit a value if any of streams will emit a data.

Use a forkJoin instead. When you work with http (I suppose you request some remote data here) - it will emit a result value if all of included streams will complete.

Upvotes: 0

tcharaf
tcharaf

Reputation: 630

You can try this:

<ng-container *ngIf="{ data1 :data$ | async, data2:data2$ | async} as data;">
<div *ngIf="data.data1 && data.data2; else loading">

  {{data.data1}}
  {{data.data2}}
</div>
<ng-template #loading>
    loading..........
 </ng-template>
</ng-container>

Upvotes: 1

LppEdd
LppEdd

Reputation: 21134

You can use the object-like syntax.

<ng-container *ngIf="{
  data1: data1$ | async,
  data2: data2$ | async
} as data">
  <div *ngIf="data.data1 && data.data2; else loading"> 
    <span>{{ data.data1 }}</span>
    <span>{{ data.data2 }}</span>
  </div>
</ng-container>
<ng-template #loading> ... </ng-template>

Or, even better, just create a new Observable which combines the other two.

data$ = combineLatest(data1$, data2$).pipe(map(([v1, v2]) => v1 && v2));

Than, just

<div *ngIf="data$ | async; else loading"> 
  ...
</div>
<ng-template #loading> ... </ng-template>

Upvotes: 13

Related Questions