Getting TypeError when trying to destroy Chart.JS object

44 Views Asked by At

I am developing an Angular application with a component that utilizes Chart.js to draw bar graphs from queries.

Software versioning info:

  • Angular CLI: 14.2.12
  • Node: 14.21.3
  • NPM: 6.14.18
  • Chart.js: 2.9.4
  • ng2-charts: 2.4.2

Please note that I have to use older versions of Chart.js and ng2-charts for the platform I am deploying to.

I have added two Chart objects as component properties and bound them to <canvas> elements on my HTML template.

import { Chart } from "chart.js"

[. . .]

  chart1: Chart;
  chart2: Chart;
<div id="bar-charts" class="row chart-container">
    <div class="card col-lg-6">
        <canvas id="chart1">
            {{chart1}}
        </canvas>
    </div>
   
    <div class="card col-lg-6">
        <canvas id="chart2">  
            {{chart2}}      
        </canvas>
    </div>
</div>

The application draws bar charts based on a query search; it can display the charts without a problem by instantiating a new Chart object via new Chart("chart", { . . . } ).

My problem arises when I want to clear existing graphs prior to making a new search query; I tried using Chart.js API's method destroy() in this custom method.

  private clearBarCharts(): void {
    this.chart1.destroy();
    this.chart2.destroy();
  }

However, calling the method generates the following TypeError:

core.mjs:6362 ERROR TypeError: Cannot read properties of undefined (reading 'destroy')
    at LiveDashboardComponent.clearBarCharts (live-dashboard.component.ts:433:1)
    at LiveDashboardComponent.onSubmit (live-dashboard.component.ts:108:1)
    at LiveDashboardComponent_Template_form_submit_7_listener (template.html:7:43)
    at executeListenerWithErrorHandling (core.mjs:14931:1)
    at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:14972:1)
    at HTMLFormElement.eval (platform-browser.mjs:459:1)
    at _ZoneDelegate.invokeTask (zone.js:443:1)
    at Object.onInvokeTask (core.mjs:26299:1)
    at _ZoneDelegate.invokeTask (zone.js:442:1)
    at Zone.runTask (zone.js:214:1)
0

There are 0 best solutions below