title: ERROR TypeError: "this.canvas is undefined" | Problem with creating a chart with angular and chart.js
body: <p>I'm trying to create a Chart with chart.js and angular</p>
  <p>Here's citydetail.component.html</p>
  <pre><code>&lt;div *ngIf=&quot;chart&quot;&gt;
      &lt;canvas #canvas&gt;&lt;/canvas&gt;
  &lt;/div&gt;
  </code></pre>
  <p>here's the code for citydetail.component.ts</p>
  <pre><code>import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
  import { Citydetails } from '../shared/citydetails';
  import { ActivatedRoute, Params, Router } from '@angular/router';
  import { Location } from '@angular/common';
  import { switchMap, scan } from 'rxjs/operators';
  import { Chart } from 'chart.js';
  // import * as Chart from 'chart.js';
  
  
  @Component({
    selector: 'app-citydetail',
    templateUrl: './citydetail.component.html',
    styleUrls: ['./citydetail.component.scss']
  })
  export class CitydetailComponent implements OnInit, AfterViewInit {
    @ViewChild('canvas', {static: false}) canvas: ElementRef;
  
    public context: CanvasRenderingContext2D;
  
    chart: Chart;
    citydetails: Citydetails;
    
  
    constructor(
      private route: ActivatedRoute,
      private router: Router,
      private location: Location,
    ) { }
  
    ngOnInit(): void {
      this.route
        .queryParams
        .subscribe( params =&gt; {
          console.log(&quot;Data: &quot;, JSON.parse(params['city']));
          this.citydetails = JSON.parse(params['city']);
          
  
        });
      
      // this.createChart();
        
    }
  
    ngAfterViewInit(): void {
      this.context = this.canvas.nativeElement.getContext('2d');
      this.chart = new Chart(this.context, {
        type: 'pie',
        data: {
          datasets: [{
            backgroundColor: [&quot;#3498db&quot;,&quot;#95a5a6&quot;,&quot;#9b59b6&quot;],
            data: [this.citydetails.active, this.citydetails.recovered, this.citydetails.deceased]
          }],
          labels: [
            'Active',
            'Recovered',
            'Deceased'
          ]
        }
      });
  
    }
  
  </code></pre>
  <p>It's showing that <strong>this.canvas</strong> is undefined. At first I was getting this error: <strong>failed to create chart: can't acquire context from the given item</strong> , and trying to solve that lead me to this.</p>
  <p>I am confused on how to proceed further.</p>