AsyncPipe in *ngIf



我试图根据 *ngIf 中可观察到isComplex$的值显示其中一个标题:

<complex-header *ngIf="isComplex$ | async; else ordinaryHeader"></complexheader>
<ng-template #ordinaryHeader>
<ordinary-header></ordinary-header>
</ng-template>

问题是*ngIf与 else 情况一起使用,而无需等待可观察量发出值。我怎样才能完成两个标头等待可观察量发出它的第一个值。

使用 angular5 *ngIf else 指令。

<div class="course-detail" *ngIf="isComplex$ | async as isComplex else ordinary">
<complex-header *ngIf="isComplex"></complex-header>
<ordinary-header *ngIf="!isComplex"></ordinary-header>
</div>
<!-- Showing ordinary header for cases when observable is not returned this can be replaced wuth loader as well-->
<ng-template #ordinary>
<ordinary-header></ordinary-header>
</ng-template> 

另请参阅 https://blog.angular-university.io/angular-reactive-templates/

不多次使用异步管道的解决方案是用异步管道将所有内容包装在ng容器中并使用*ngFor。但是要使用*ngForisComplex$必须始终发出可迭代对象。因此,我们需要一个新的可观察量在模板中使用:

isComplexIterable$ = isComplex$.pipe(map(isComplex => [isComplex]))
<ng-container *ngFor="let isComplex of isComplexIterable$ | async">
<complex-header *ngIf="isComplex"></complexheader>
<ordinary-header *ngIf="!isComplex"></ordinary-header>
</ng-container>

最新更新