簡體   English   中英

Angular 5 ngOnChanges在子組件中僅觸發一次

[英]Angular 5 ngOnChanges fires only once in child component

我有一個包含復雜輸入(某些圖表數據)的子組件。 我收到API響應后,通過Angular 5中的@Input()裝飾器從父組件發送此圖表數據。 因此,每次在父組件(即OnChange Lifecyle)上更改圖表時,我都需要根據API響應同步圖表。 但不幸的是,我無法使它正常工作。 我嘗試用基本數字類型設置一個虛擬輸入字段,並將其遞增,但徒勞無功。 這是我的實現:

子圖表組件:

export class ChartComponent implements OnInit, OnChanges {

  @Input() chartData;
  @Input() triggerChart;

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }

}

父組件html:

<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">

父組件:

this.chartService.getChartData(params).subscribe(res => {
  this.chartData = res;
  this.triggerChartData++;
});

PS:作為標題的ngOnChanges表示僅在組件使用未定義的值初始化時才觸發一次。

感謝@HoangDucNguyen,這是工作代碼:

this.chartService.getChartData(params).subscribe(res => {
  this.chartData = res;
  this.changeDetectorRef.detectChanges();
});

當然,您將需要從@ angular / core導入ChangeDetectorRef類,並將其注入到構造函數中。

說明:
當變量在角度上下文之外(在這里:這是rxJs上下文)更改時,Angular無法檢測到變量的更改。 因此,您需要手動觸發檢測變化角度方法。

官方文檔: https : //angular.io/api/core/ChangeDetectorRef

您必須使用changeDetectorRef

this.cd.markForCheck();
if (!this.cd['destroyed']) {
    this.cd.detectChanges();
}

暫無
暫無

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

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