[英]Angular 5 ngOnChanges fires only once in child component
I have a child component that contains complex input (some chart data). 我有一个包含复杂输入(某些图表数据)的子组件。 I am sending this chart data from the parent component through the @Input() decorator in Angular 5 after getting API response. 我收到API响应后,通过Angular 5中的@Input()装饰器从父组件发送此图表数据。 So, I need to sync the chart according with the API response every time it gets changed on the parent component, hence, the OnChange Lifecyle. 因此,每次在父组件(即OnChange Lifecyle)上更改图表时,我都需要根据API响应同步图表。 But unfortunately, I am not able to get this to work properly. 但不幸的是,我无法使它正常工作。 I tried with setting a dummy input field with basic number type and increment it but in vain. 我尝试用基本数字类型设置一个虚拟输入字段,并将其递增,但徒劳无功。 Here's my implementation: 这是我的实现:
Child chart component: 子图表组件:
export class ChartComponent implements OnInit, OnChanges {
@Input() chartData;
@Input() triggerChart;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
Parent component html: 父组件html:
<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">
Parent component: 父组件:
this.chartService.getChartData(params).subscribe(res => {
this.chartData = res;
this.triggerChartData++;
});
PS: The ngOnChanges as the title indicates only fires once when the component initializes with undefined values. PS:作为标题的ngOnChanges表示仅在组件使用未定义的值初始化时才触发一次。
Thanks to @HoangDucNguyen, here's the working code: 感谢@HoangDucNguyen,这是工作代码:
this.chartService.getChartData(params).subscribe(res => {
this.chartData = res;
this.changeDetectorRef.detectChanges();
});
Of course you will need to import the ChangeDetectorRef class from @angular/core and inject it in your constructor. 当然,您将需要从@ angular / core导入ChangeDetectorRef类,并将其注入到构造函数中。
Explanation: 说明:
When variables are changed outside of the angular context (in here: it's the rxJs context), Angular isn't able to detect changes on the variables. 当变量在角度上下文之外(在这里:这是rxJs上下文)更改时,Angular无法检测到变量的更改。 So, you need to manually fire the detect changes angular method. 因此,您需要手动触发检测变化角度方法。
Official doc: https://angular.io/api/core/ChangeDetectorRef 官方文档: https : //angular.io/api/core/ChangeDetectorRef
you must use changeDetectorRef
您必须使用changeDetectorRef
this.cd.markForCheck();
if (!this.cd['destroyed']) {
this.cd.detectChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.