簡體   English   中英

angular2在模板中顯示計算數據

[英]angular2 displaying computed data in template

我剛剛開始使用Angular2並遇到以下問題。 模板(主要組件):

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

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

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

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

我應該在哪里注入代碼來計算someCompValue? 我嘗試在構造函數()中執行此操作,但那一刻尚未分配數據 (= null)。

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

另請參見OnChanges Livecycle回調。

使用ngOnInitref ):

在Angular初始化數據綁定的輸入屬性之后,初始化指令/組件。

因此在組件中:

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

    constructor() { ... }

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

編輯:查看來自GünterZöchbauer的答案, 請注意 :如果在組件初始化時只計算一次數據, 使用ngOnInit 如果要在開始時計算數據,並在每次輸入更改時重新計算數據,請使用ngOnChanges (根據Günter的回答)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM