2016-04-22 25 views
1

我剛剛開始使用Angular2並引發了以下問題。 模板(主要成分):angular2在模板中顯示計算的數據

<span *ngFor="#data of dataset" > 
    <data-widget [data]="data"></data-widget> 
</span> 

模板(窗口小部件組件):

<div>{{someCompValue}}</div> 

從一組屬性的數據內創建someCompValue的是所需要的值成員變量。

我應該在哪裏注入代碼來計算someCompValue? 我試圖在構造函數()內完成它,但那一刻尚未分配(=空)數據尚未分配(=空)。

回答

2

ngOnInit使用(ref):

初始化指令/組件角初始化數據綁定輸入屬性之後。

所以,在組件:

@Component(...) 
export class DataWidget { 
    @Input data: Xxxx; 

    constructor() { ... } 

    ngOnInit() { 
     // this.data should be set and ready to use here 
    } 
} 

編輯:看從岡特Zöchbauer,一個答案:使用ngOnInit如果數據是在分量來計算只有一次初始化;使用ngOnChanges(根據Günter的答案)如果要在開始時計算數據並在每次輸入更改時重新計算。

2
@Component({ 
    selector: 'data-widget', 
    template`<div>{{someCompValue}}</div>`}) 
class DataWidget { 
    @Input() data; 
    ngOnChanges(change) { 
    this.someCompValue = doCalculationBasedOnData(); 
    } 
} 

另請參閱OnChanges livecycle回調。