[Chartjs]-GetElementById on element from parent component returns null, when called in ngAfterViewInit() of child component

2๐Ÿ‘

โœ…

you can use @ViewChild decorator to query an element from component template

BarChartComponet

  @ViewChild('chartElm', { static: true }) public chartElm: ElementRef;

  ngAfterViewInit() {
    this.addchart(); 
  }

  public addchart(){
    var canvas = <HTMLCanvasElement> this.chartElm.nativeElement; // ๐Ÿ‘ˆ

    var ctx = canvas.getContext("2d");
    var mychart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: ['Red', 'Blue'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19],
              backgroundColor: 'lightgreen',
              borderColor: 'blue',
              borderWidth: 1
          }]
      },
      options: {
          legend: {
            display: false
        },
      }
    });
  }

template

<div style="width:400px; height:100%;"> 
  <canvas #chartElm ></canvas>
</div>

demo ๐Ÿš€๐Ÿš€

Leave a comment