title: Why my canvas drawImage not showing up in angular2 component
body: <p>I am writing a canvas which draws an image in the component of angular2.</p>
  
  <p>Here is the canvas.component.ts</p>
  
  <pre><code>export class BoardComponent implements  OnInit,  AfterViewInit, AfterViewChecked {
  
    @ViewChild("visualization") visualization: ElementRef;
    @ViewChild('img') img: ElementRef;
  
    private context: CanvasRenderingContext2D;
    private element: HTMLImageElement;
  
    src: string;
    width: number
    height: number
  
    constructor() {
      this.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
    }
  
    ngOnInit() {
      this.width = 400;
      this.height = 400;
    }
  
    ngAfterViewInit() {
      this.context = this.visualization.nativeElement.getContext("2d");
      this.element = this.img.nativeElement;
    }
  
    ngAfterViewChecked() {
      this.context.clearRect(0, 0, this.width, this.height);
      console.log('drawImage');
      // this prints an image element with src I gave
      console.log(this.element);
      this.context.drawImage(this.element, 0, 0, this.width, this.height);
    }
  }
  </code></pre>
  
  <p>and here is the template</p>
  
  <pre><code>&lt;img #img src="{{src}}" style='display: none;' /&gt;
  &lt;canvas #visualization width="{{width}}" height="{{height}}"&gt;&lt;/canvas&gt;`
  </code></pre>
  
  <p>it looks like the image has been loaded, but my canvas is still empty.</p>
  
  <p>I have found many similar questions, but none of them use angular2.</p>
  
  <p>for example, the answer from this one <a href="https://stackoverflow.com/questions/15048279/drawimage-not-working">drawImage() not working</a> is that you should wait until the image is loaded.</p>
  
  <p>But I don't know how to check this situation in angular way.</p>
  
  <p>Any suggestion?</p>
  
  <p>thanks. </p>
  
  <h2>Edit</h2>
  
  <p>I found that maybe the reason is that the image is not loaded when I render it to the canvas.</p>
  
  <p>I add the following code and resize my page, and the canvas does show up.</p>
  
  <pre><code>@HostListener('window:resize')
  resize() {
      this.render();
    }
  render() {
      this.context.clearRect(0, 0, this.width, this.height);
      this.context.drawImage(this.element, 0, 0, this.width, this.height);
   }
  </code></pre>
  
  <p>If this is the reason, the question changes, what is the proper way to add a event listener (like img.onLoad) to the html element in angular2?</p>