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

标签 angular angular2-template ng-template

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

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

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

最佳答案

在这里阅读文档 https://angular.io/guide/structural-directives特别是对于

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

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular desugars it in two stages. First, it translates the *ngIf="..." into a template attribute, template="ngIf ...", like this.

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

Then it translates the template attribute into a element, wrapped around the host element, like this.

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

  • The *ngIf directive moved to the element where it became a property binding,[ngIf].
  • The rest of the , including its class attribute, moved inside the element.

因此我们有 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 ( not recommended )

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

关于angular - 为什么 *ngIf 不适用于 ng-template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837756/

相关文章:

Angular 2+ 过滤器 *ngFor 带 Material 分页器的表

javascript - 如何在 angular2 模板中使用 Electron 的 webview html 元素?

angular - 如何将上下文对象传递给使用 ng-template 创建的嵌入式 View

Angular 动态模板渲染,如 ui 网格单元格模板(在 parent 的 colDefs 中声明的模板)

Angular 5 在路由更改之前添加事件

html - 如何根据下拉列表中的选定数字生成表单输入字段(选择)

javascript - 无法导入外部 NPM 包来制作 Angular 库

Angular 2 Material md 输入验证

来自 HTTP 调用的 Angular 动态模板

javascript - 找不到模板-使用 angularjs ngCart 构建电子商务购物车