子组件中的ExpressionChangedAfterItHasBeenCheckedError

Blo*_*nat 5 angular

我有一个父组件,它每秒更新其数组myValue。在子组件中,我想创建一个图表,该图表使用此数组作为数据,并在每次父组件更新时也进行更新。

当我运行此应用程序时,出现以下错误:

错误:ExpressionChangedAfterItHasBeenCheckedError:检查表达式后,表达式已更改。先前的值:“ hidden: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);
          }
        );
      });
  }
...

}
Run Code Online (Sandbox Code Playgroud)

父模板如下所示:

<ul>
  <li *ngFor="let value of myValues">
    <p>{{value.name}}</p>
  </li>
</ul>

<app-value-chart [chartData] = myValues></app-value-chart>
Run Code Online (Sandbox Code Playgroud)

这是我的孩子部分:

@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);
  }
...
}
Run Code Online (Sandbox Code Playgroud)

子模板:

  <canvas id="canvas" responsive>{{ chart }}</canvas>
Run Code Online (Sandbox Code Playgroud)

我该如何解决我的问题?

我使用Angular 6。

Con*_*Fan 6

您可以在本文中找到有关该异常的详细说明。消除异常的一种技术是使用以下命令强制进行更改检测ChangeDetectorRef.detectChanges

export class ValueChartComponent implements AfterViewInit {

    constructor(private cd: ChangeDetectorRef) { }

    ngAfterViewInit(): void {
        ...
        this.cd.detectChanges();
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

另一种技术是使用setTimeout以下方法异步运行处理程序代码:

export class ValueChartComponent implements AfterViewInit {

    ngAfterViewInit(): void {
        setTimeout(() => {
            ...
        });
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)