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

后端 未结 2 1253
别那么骄傲
别那么骄傲 2021-01-06 01:43

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         


        
相关标签:
2条回答
  • 2021-01-06 02:07

    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>
    
    0 讨论(0)
  • 2021-01-06 02:26

    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>
    
    0 讨论(0)
提交回复
热议问题