Home > Blockchain >  Dynamic id with canvas on html and angular
Dynamic id with canvas on html and angular

Time:10-29

i want to set a dynamic id for my report (canvas) in my html with angular but im getting an error if u can help me pls, this is the code of my class and my html

export class CardKPIReporteComponent implements OnInit {
  @BlockUI() blockUI: NgBlockUI;
  @Input() datos_kpi_reporte: any
  fetcher: any
  arrayListaKpis: any
  tituloreporte: any
  id: any = 1
  chartBienesUbicacion: any;
  constructor(private procesoOperacionService: ProcesoOperacionesService
  ) {

  }

  ngOnInit() {
    this.tituloreporte = this.datos_kpi_reporte.servicio_nombre
    this.id = this.datos_kpi_reporte.cont //this.id = 1
    this.Grafico2();

  }
  Grafico2() {
    // this.id = this.datos_kpi_reporte.cont

    var nombrechart = "Reporte"   this.datos_kpi_reporte.cont
    this.chartBienesUbicacion = new Chart(nombrechart, {
      type: 'pie',
      data: {
        labels: ['ENTREGADO', 'NO ENTREGADO', '1', '1'],
        datasets: [
          {
            label: 'Cantidad',
            data: ['1', '1', '1', '1'], // this.chartsTotal,
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor:
              'rgba(54, 162, 235, 1)',
            borderWidth: 1
          }
        ]
      },
      options: {
        title: {
          text: nombrechart,
          display: true
        },
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    });
  }
}

    <mat-card-content>
        <!--<app-alert></app-alert> -->
        <div class="row">
            <canvas id="Reporte{{ this.id }}"></canvas>
        </div>
    </mat-card-content>

ive been trying this way but im getting this error: "Chart.js:8459 Failed to create chart: can't acquire context from the given item"

CodePudding user response:

This is happening because your trying to add the canvas before you set the id in the template. You need to set the ID in the template, and after the view initializes then add your chart.

make sure you implement AfterViewInit and update your code as such.

  ngOnInit() {
    this.tituloreporte = this.datos_kpi_reporte.servicio_nombre
    this.id = this.datos_kpi_reporte.cont
  }

  ngAfterViewInit() {
    this.Grafico2();
  }
  • Related