【问题标题】:Destroy ng2-charts before navigating to another component在导航到另一个组件之前销毁 ng2-charts
【发布时间】:2021-12-29 12:37:58
【问题描述】:
我在每条路线上都创建了图表。
当我尝试从一个组件导航到另一个组件时,我收到此错误并且页面已损坏。 (请看下面的截图)
有什么解决办法吗?
谢谢
<canvas baseChart id="barChart" #barChart [datasets]="chartData" [labels]="barChartLabels"
[options]="barChartOptions" [chartType]="chartType"></canvas>
【问题讨论】:
标签:
html
angular
angular7
ng2-charts
ondestroy
【解决方案1】:
在销毁图表之前检查图表是否存在:
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();
}
}