Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

606
Views
Error de Chart js en angular: Canvas ya está en uso. El gráfico con ID '0' debe destruirse antes de poder reutilizar el lienzo. ¿Arreglar?

Básicamente, al hacer clic en div (jquery), tengo una ventana emergente modal de arranque que tiene un gráfico. El gráfico funciona bien y la representación es perfecta, el problema surge cuando hago clic en otro div.

Aquí está mi HTML

 <div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="card"> <div class="text-right cross"> hello<i class="fa fa-times"></i> </div> <div id="chartDiv" *ngIf="chart"><canvas #chart>{{ chart }}</canvas></div> </div> </div> </div>

En una nota aparte, estoy usando Chart.register(...registerables) en mi constructor. Aquí va mi TS (solo el código relevante):

 import { Chart, registerables } from 'chart.js'; export class HomeComponent implements OnInit{ @ViewChild('chart') canvas: ElementRef; chart: any = []; ngOnInit(): void { $('#myModal').on('hide.bs.modal', function () { $(".canvas").remove(); }) $('#myModal').on('show.bs.modal', function () { $("div.chart").append('<canvas #chart>{{chart}}</canvas>'); $('#chart').trigger('focus') }) } divClick() { $('#myModal').modal('show'); this.chart = this.getChartData() } getChartData(): Chart { this.chart = new Chart(this.canvas.nativeElement.getContext('2d'), {data}) //please don't worry about data its coming from api and it works fine return this.chart } }

Todo esto es de muy alto nivel, pero estoy feliz de incluir cualquier otro código necesario. Investigué tantos artículos y formas de solucionar este error, pero no pude encontrar ninguno. Si puede indicarme un recurso donde se implemente Chart js usando Angular, sería útil. Además, probé la función "destruir" en this.chart pero tampoco funciona. ¿Hay alguna otra forma de usar esto en lugar de exponer el lienzo? Simplemente no sé lo que estoy haciendo mal. Incluso intenté eliminar y volver a agregar clases de lienzo a través de jquery (en onInit), pero eso tampoco funciona. (Chartjs v3.7.0)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Estás haciendo todo bien, y estás tan cerca. Creo que no hay necesidad de almacenar nada en este gráfico. Simplemente regrese y renderice. Para corregir su error de múltiples instancias, simplemente agregue una verificación de la existencia del gráfico antes de renderizar.

 divClick() { var chartExist = Chart.getChart("myChart"); // <canvas> id if (chartExist != undefined) chartExist.destroy(); $('#myModal').modal('show'); this.getChartData() } getChartData(): any { return new Chart(this.canvas.nativeElement.getContext('2d'), {data}) }

En su HTML, simplemente agregue id para el gráfico

 <canvas id="myChart" #chart>{{ chart }}</canvas>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!