To achieve this task, utilize the @ViewChild
method.
In your component class, implement the following steps:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
name: 'my-component',
// ensure variable name matches myCanvas
template: `<canvas #myCanvas></canvas>`
})
export class myComponent implements AfterViewInit {
@ViewChild('myCanvas')
canvas: ElementRef<HTMLCanvasElement>;
context: CanvasRenderingContext2D;
ngAfterViewInit(): void {
this.context = this.canvas.nativeElement.getContext('2d');
}
}
Avoid relying on document
as much as possible to prevent future complications. Using @ViewChild
is advantageous over direct DOM manipulation in Angular because it allows for targeted modifications without needing to search the DOM each time.
Refer to this demo for a comprehensive example.
Update
For Angular 8, adjust the ViewChild
usage as follows:
@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;
Visit How should I use the new static option for @ViewChild in Angular 8? for further details.