'Destroy ng2-charts before navigating to another component

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>


Solution 1:[1]

?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();
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lidiya Parshina