Angular 5 ngOnChanges 在 child 组件中仅触发一次
Angular 5 ngOnChanges fires only once in child component
我有一个包含复杂输入(一些图表数据)的 child 组件。
在获得 API 响应后,我通过 Angular 5 中的 @Input() 装饰器从 parent 组件发送此图表数据。因此,每次在 parent 组件上发生更改时,我都需要根据 API 响应同步图表,因此,OnChange 生命周期。但不幸的是,我无法让它正常工作。我尝试使用基本数字类型设置一个虚拟输入字段并递增它,但没有成功。这是我的实现:
Child 图表组件:
export class ChartComponent implements OnInit, OnChanges {
@Input() chartData;
@Input() triggerChart;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
Parent分量html:
<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">
Parent分量:
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 class 并将其注入您的构造函数。
解释:
当变量在 angular 上下文之外更改时(此处:它是 rxJs 上下文),Angular 无法检测到变量的更改。因此,您需要手动触发检测更改 angular 方法。
你必须使用 changeDetectorRef
this.cd.markForCheck();
if (!this.cd['destroyed']) {
this.cd.detectChanges();
}
我有一个包含复杂输入(一些图表数据)的 child 组件。 在获得 API 响应后,我通过 Angular 5 中的 @Input() 装饰器从 parent 组件发送此图表数据。因此,每次在 parent 组件上发生更改时,我都需要根据 API 响应同步图表,因此,OnChange 生命周期。但不幸的是,我无法让它正常工作。我尝试使用基本数字类型设置一个虚拟输入字段并递增它,但没有成功。这是我的实现:
Child 图表组件:
export class ChartComponent implements OnInit, OnChanges {
@Input() chartData;
@Input() triggerChart;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
Parent分量html:
<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">
Parent分量:
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 class 并将其注入您的构造函数。
解释:
当变量在 angular 上下文之外更改时(此处:它是 rxJs 上下文),Angular 无法检测到变量的更改。因此,您需要手动触发检测更改 angular 方法。
你必须使用 changeDetectorRef
this.cd.markForCheck();
if (!this.cd['destroyed']) {
this.cd.detectChanges();
}