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