我刚开始使用 Angular2 并遇到了以下问题。 模板(主要组件):
<span *ngFor="#data of dataset" >
<data-widget [data]="data"></data-widget>
</span>
模板(小部件组件):
<div>{{someCompValue}}</div>
someCompValue 的值需要从 data 成员变量中的一组属性创建。
我应该在哪里注入(inject)代码来计算 someCompValue? 我尝试在 constructor() 中执行此操作,但那一刻 data 尚未分配 (=null)。
最佳答案
使用 ngOnInit
( ref ):
Initialize the directive/component after Angular initializes the data-bound input properties.
所以在组件中:
@Component(...)
export class DataWidget {
@Input data: Xxxx;
constructor() { ... }
ngOnInit() {
// this.data should be set and ready to use here
}
}
编辑:查看 Günter Zöchbauer 的回答,注意:如果要在组件初始化时只计算一次数据,请使用 ngOnInit
;如果要在开始时计算数据并在每次输入更改时重新计算,请使用ngOnChanges
(根据 Günter 的回答)。
关于javascript - angular2 在模板中显示计算数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36791701/