我在我的父'my-app'組件中使用了angular2組件'my-tree'。 「我的應用程序內」是如下:Angular2:嵌套* ngFor導致'檢查後表達式發生了變化'
@Component({
selector: 'my-app',
providers: [],
template: `
<my-tree *ngFor="#node of nodes" [title]="node">
<my-tree *ngFor="#subNode of getSubNodes(node)" [title]="subNode">
</my-tree>
</my-tree>
`,
directives: [MyTree]
})
export class App {
constructor() {
this.nodes = ['Angular2', 'typescript', 'js']
}
getSubNodes(node: string) {
if(node === 'Angular2') {
return ['2.0.0', '1.4.2']
}
if (node === 'typescript') {
return ['1.7.3'];
}
if (node === 'js') {
return ['es-6'];
}
}
}
我的樹是一個簡單的組件 -
@Component({
selector: 'my-tree',
providers: [],
inputs: ['title'],
template: `
<ul>
<li><span>{{title}}</span></li>
<ng-content></ng-content>
</ul>
`,
directives: []
})
export class MyTree {
private title: string;
}
當這樣執行,控制檯登錄與下面的錯誤 - 表達「getSubNodes(節點)在App @ 2:15'被檢查後發生了變化。以前的值:'2.0.0,1.4.2'。當前值:'2.0.0,1.4.2'。
有關實際代碼,請參見此plunk。
我的代碼中的想法是創建一個樹(只是一個例子),第一個級別來自一個數組(硬編碼值),第二個級別來自一個函數,返回給定當前節點的下一個集合或價值)從第一級。 而且它調用這個函數的地方在角色抱怨表達式被檢查後被改變。雖然報告的值與錯誤消息中的前面的報告完全相同。 我在SO上搜索了這個錯誤,並且發現了很少的參考文獻,但是他們大多建議引用更改檢測。我無法理解爲什麼這是必需的,以及如何做到這一點。我還讀到,這只是一條診斷消息,並沒有在生產模式下拋出。
是不是可以在* ngFor中調用一個函數?應該做些什麼來擺脫這個錯誤?
好吧,現在我明白了錯誤信息的原因。但是定義總是滿足這個標準的返回值可能並不總是可能的。函數調用可能並不總是以這種方式總是返回。所以基本上這意味着功能不應該被使用? – tyrion
您可以選擇@Component({changeDetection:ChangeDetectionStrategy.OnPush})'並通知Angular有關更改。見https://github.com/angular/angular/issues/4746或者實現'doCheck' https://angular.io/docs/js/latest/api/core/DoCheck-interface.html –
這真的很有幫助。 – tyrion