I have an angular2 component 'my-tree' which I am using in my parent 'my-app' component. 'my-app' is as below:
@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'];
}
}
}
my-tree is a simple component -
@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;
}
When this is executed, the console is logged with following errors - Expression 'getSubNodes(node) in App@2:15' has changed after it was checked. Previous value: '2.0.0,1.4.2'. Current value: '2.0.0,1.4.2'.
See this plunk for actual code.
The idea in my code is to create a tree( just an example), the first levels come from an array(hard coded values), the second level come from a function that returns the next set given the current node(or value) from the first level. And its the call to this function where angular complains for the expression being changed after it was checked. Though the value is reported exactly same as it was earlier in the error message. I searched for this error on SO, and found few references, but mostly they suggest to invoke change detection. I am unable to understand why this is required and also how to do that. I also read that this is a diagnostic message only and it is not thrown in production mode.
Is it not possible to call a function within an *ngFor? What should be done to get rid of this error?