我有一个父组件,它每秒更新一次其数组myValue
。在子组件中,我想创建一个图表,该图表使用该数组作为数据,并在每次父组件更新时更新。
当我运行此应用程序时,我收到此错误:
错误:ExpressionChangedAfterItHasBeenCheckedError:表达式有
检查后更改了。以前的值:“隐藏:true”。当前的
值:'隐藏:假'。
这是我的父组件:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements AfterContentInit, OnDestroy {
private myValues: MyValue[];
private alive: boolean;
constructor(private valueService: ValueService) {
this.alive = true;
this.myValues = [];
}
ngAfterContentInit(): void {
TimerObservable.create(0, 1000)
.takeWhile(() => this.alive)
.subscribe(() => {
this.valueService.doSmth().subscribe(
value => {
this.myValues.push(value);
}
);
});
}
...
}
父模板如下所示:
<ul>
<li *ngFor="let value of myValues">
<p>{{value.name}}</p>
</li>
</ul>
<app-value-chart [chartData] = myValues></app-value-chart>
这是我的子组件:
@Component({
selector: 'app-value-chart',
templateUrl: './value-chart.component.html',
styleUrls: ['./value-chart.component.scss']
)}
export class ValueChartComponent implements AfterViewInit {
@Input() chartData: MyValue[];
chart: any;
ngAfterViewInit(): void {
this.createChart(); // creates chart with ChartJS
const tmp: number[] = [];
for (let i = 0; i < this.chartData.length; i++) {
tmp.push(this.chartData[i].x);
}
this.chart.data.datasets[0].data = tmp;
this.chart.update(0);
}
...
}
子模板:
<canvas id="canvas" responsive>{{ chart }}</canvas>
我该如何解决我的问题?
我用的是 Angular 6。
您可以在以下位置找到有关该异常的详细说明本文。消除异常的一种技术是强制进行更改检测ChangeDetectorRef.detectChanges
:
export class ValueChartComponent implements AfterViewInit {
constructor(private cd: ChangeDetectorRef) { }
ngAfterViewInit(): void {
...
this.cd.detectChanges();
}
...
}
另一种技术是异步运行处理程序代码setTimeout
:
export class ValueChartComponent implements AfterViewInit {
ngAfterViewInit(): void {
setTimeout(() => {
...
});
}
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)