【发布时间】:2016-04-30 04:58:39
【问题描述】:
我有一个 angular2 组件“my-tree”,我在我的父级“my-app”组件中使用它。 “我的应用”如下:
@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 是一个简单的组件 -
@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(node) in App@2:15' 在检查后已更改。以前的值:'2.0.0,1.4.2'。当前值:'2.0.0,1.4.2'。
查看plunk 获取实际代码。
我的代码中的想法是创建一棵树(只是一个例子),第一层来自一个数组(硬编码值),第二层来自一个函数,它返回给定当前节点的下一组(或值)从第一级。 并且它调用这个函数,其中角度抱怨表达式在检查后被更改。尽管报告的值与错误消息中的先前值完全相同。 我在 SO 上搜索了这个错误,发现很少有参考资料,但他们大多建议调用更改检测。我无法理解为什么需要这样做以及如何做到这一点。我还读到这只是一条诊断消息,不会在生产模式下抛出。
不能在 *ngFor 中调用函数吗?应该怎么做才能摆脱这个错误?
【问题讨论】:
标签: angular