为什么*ngIf与ng-template无关?

fac*_*urn 39 angular2-template ng-template angular

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

<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>
Run Code Online (Sandbox Code Playgroud)

我有包含row和的数据集seatNo,但它似乎没有在模板中打印.这是什么问题?

Fet*_*rij 77

请阅读此处的文档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].
  • 其余部分(包括其class属性)移动到元素内部.

所以我们有 ng-container

 <ng-container *ngIf="seat.section">
    Section {{seat.section}} ,
 </ng-container>
Run Code Online (Sandbox Code Playgroud)

或使用span或div或常规html标记.

 <span *ngIf="seat.section">
    Section {{seat.section}} ,
 </span>
Run Code Online (Sandbox Code Playgroud)

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

<ng-template [ngIf]="seat.section">
  Section {{seat.section}} ,
</ng-template>
Run Code Online (Sandbox Code Playgroud)

  • 这里有人:/sf/ask/3323462901/#47478041 想知道为什么你说不建议使用 ng-template。 (2认同)