If you don't want to upset the corner gods, use @ViewChild
In your HTML, add a link to the template.
<canvas #myCanvas></canvas>
In your class, do the following.
import { ViewChild, ElementRef } from '@angular/core'; ... // Somewhere above your class constructor @ViewChild('myCanvas') myCanvas: ElementRef; public context: CanvasRenderingContext2D; // Somewhere under the class constructor we want to wait for our view // to initialize ngAfterViewInit(): void { this.context = (<HTMLCanvasElement>this.myCanvas.nativeElement).getContext('2d'); }
Try not to use the document for as long as it can bite you in the long run. In addition, using @ViewChild takes precedence over querying the DOM after compiling the application. Angular already knows in advance which element it should make changes to, instead of looking for it in the DOM.
Check out this demo for a complete example.
Refresh
For angular 8 you need to use ViewChild like this.
@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;
See How do I use the new static option for @ViewChild in Angular 8? for more information
source share