NgIf 多个模板变量

NgIf multiple template variables

我发现

<div
  *ngIf="asyncCond$ | async as c1 && cond2"
></div>

行不通。 有没有一种方法可以在一个指令中定义具有多个别名的多个条件?

喜欢asyncCond1$ | async as c1 && asyncCond2$ | async as c2等等。添加 () 似乎没有任何影响。

您只能使用结构指令声明一个 as 别名,但我就是这样做的。

您可以使用 combineLatest() 将多个可观察对象组合在一起并创建一个在模板中使用的状态对象。您创建一个对象,其中的属性是多个可观察值的快照。

   this.state$ = combineLatest(asyncCond1$, asyncCond2$, asyncCond3$).pipe(
      map(([asyncCond1, asyncCond2, asyncCond3]) => ({asyncCond1, asyncCond2, asyncCond3}))
   );

现在您可以在模板中像这样使用状态对象了。

<ng-container *ngIf="state$ | async as state">
    <div *ngIf="state.asyncCond1 && state.asyncCond2"></div>
    <div *ngIf="state.asyncCond3"></div>
    <div>
       {{state.asyncCond1 ? "Yes" : "No"}}
    </div>
</ng-container>

对于使用多个 observable 的更复杂的模板,使用起来会容易得多。