繁体   English   中英

ngFor和ngIf Angular2的模板标签问题

[英]Template tag issue with ngFor and ngIf Angular2

我在尝试在模板标签中使用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>

我一直在收到错误

无法读取undefined的属性'title'

在以下情况下,错误消失:

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

plunker中完整代码的链接

任何人都可以解释为什么会这样吗?

谢谢!

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

请改用

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

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

@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>
  `,
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM