Destroy ng2-charts before navigating to another component

367 Views Asked by At

I created charts in each route.

When I try to navigate from one component to another component I am getting this ERROR and the page is broken. (please see the screenshot below)

Any solutions?

Thanks

enter image description here

<canvas baseChart id="barChart" #barChart [datasets]="chartData" [labels]="barChartLabels"
[options]="barChartOptions" [chartType]="chartType"></canvas>

1

There are 1 best solutions below

0
Lidiya Parshina On

Сheck if the chart exists before destroying it:
app.component.ts

import {BaseChartDirective} from 'ng2-charts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnDestroy {
  @ViewChild('barChart') chart: BaseChartDirective;

  ngOnDestroy() {
    if (this.chart) this.chart.ngOnDestroy();
  }
}