【问题标题】:Template tag issue with ngFor and ngIf Angular2ngFor 和 ngIf Angular2 的模板标签问题
【发布时间】:2017-05-24 16:41:32
【问题描述】:

我在尝试在模板标签中使用 ngFor 和 ngIf 时遇到了一个奇怪的问题。我试图在 Analyst 对象中显示标签标题,如下所示:

分析对象:

class Analyst {
  private _properties = {labels: [{title:'a'}]};

  get labels() {
    return this._properties.labels;
  }  

  set labels(labels:Array<string>) {
    this._properties.labels = labels;
  }      
}

组件模板:

<div *ngFor="let analyst of analysts; let i = index">
  <h2>Analyst {{i}}</h2>
  <template ngFor let-label [ngForOf]="analyst.labels"
                              [ngIf]="analyst.labels.length > 0">
    <div>{{label.title}}</div>
  </template>
</div>

我不断收到错误

无法读取未定义的属性“标题”

在以下情况下错误消失:

  • 删除 [ngIf] 时
  • 当使用 json 管道而不是标题属性 {{label| json}}。打印到屏幕的 json 字符串包含 title 属性。

plunker中完整代码的链接

谁能解释一下为什么会这样?

谢谢!

【问题讨论】:

    标签: angular


    【解决方案1】:

    同一元素上不能有多个结构指令

    改为使用

    <div *ngFor="let analyst of analysts; let i = index">
      <h2>Analyst {{i}}</h2>
      <ng-container *ngFor="let label of analyst.labels">
        <div *ngIf="label.length > 0">{{label.title}}</div>
      </ng-container>
    </div>
    

    【讨论】:

    • 你可以使用&lt;template&gt;标签,但是因为它需要不同的绑定语法,他们引入了&lt;ng-container&gt;&lt;ng-container&gt; 也只是一个不添加到 DOM 的虚拟元素,但允许您使用与任何其他元素相同的语法。
    • 我的印象是,使用具有不同绑定语法的模板标签可以让您使用多个结构指令....每天学习新事物:) 谢谢!
    • 不,模板标签(以前是 - 现在是 &lt;ng-content&gt;)通常在您在普通元素上有 2 个结构指令时使用,将 其中一个 2 移出其明确的&lt;template&gt; 标签。
    【解决方案2】:

    同一元素上不能有两个以上的结构指令

    @Component({
      selector: 'my-app',
      template: `
      <button (click)="addLabel()">add</button>
      <div *ngFor="let analyst of analysts; let i = index">
        <h2>Analyst {{i}}</h2>
        <template ngFor [ngForOf]="analyst.labels" let-label>
                <div *ngIf ="analyst.labels.length > 0">
              <div>{{label.title}}</div>
              </div>
          </template>
        </div>
      `,
    })
    

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 2018-08-17
      • 2018-06-20
      • 2020-06-09
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2016-09-17
      相关资源
      最近更新 更多