64

我在模板中有一个条件如下:

<ng-container>
    <p *ngFor="let seat of InfoDetails?.seatInfo">
        <template *ngIf="seat.section">
            Section {{seat?.section}} ,
        </template>
        <template *ngIf="seat.row">
            Row {{seat?.row}},
        </template>
        <template *ngIf="seat.seatNo">
            Seat number {{seat?.seatNo}}
        </template>
    </p>
</ng-container>

我有包含rowand的数据集seatNo,但它似乎没有在模板中打印。这里有什么问题?

4

1 回答 1

119

阅读此处的文档https://angular.io/guide/structural-directives特别适用于

<div *ngIf="hero" >{{hero.name}}</div>

星号是更复杂的东西的“语法糖”。在内部,Angular 分两个阶段对其进行脱糖。首先,它将 *ngIf="..." 转换为模板属性 template="ngIf ...",如下所示。

<div template="ngIf hero">{{hero.name}}</div>

然后它将模板属性转换为一个元素,包裹在宿主元素周围,就像这样。

<ng-template [ngIf]="hero"> <div>{{hero.name}}</div></ng-template>

  • *ngIf 指令移动到它成为属性绑定的元素,[ngIf]。
  • 的其余部分,包括其类属性,在元素内移动。

所以我们有ng-container

 <ng-container *ngIf="seat.section">
    Section {{seat.section}} ,
 </ng-container>

或使用 span 或 div 或常规 html 标签。

 <span *ngIf="seat.section">
    Section {{seat.section}} ,
 </span>

或者如果您仍想使用 ng-template(不推荐

<ng-template [ngIf]="seat.section">
  Section {{seat.section}} ,
</ng-template>
于 2017-06-30T03:36:03.927 回答