为什么* ngIf不适用于ng-template?

用户7426734:

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

<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>

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

费特拉里(Fetrarij):

在此处阅读文档https://angular.io/guide/structural-directives尤其适用于

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

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

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

然后,它将template属性转换为一个元素,包裹在宿主元素中,如下所示。

<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>

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

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

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

<ng-template [ngIf]="seat.section">
  Section {{seat.section}} ,
</ng-template>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章