When we try to use Chart JS inside an Angular application, we may come across the error message “Property ‘getContext’ does not exist on type ‘HTMLElement’” given by TypeScript.

Reason for the Error Message “Property ‘getContext’ does not exist on type ‘HTMLElement'”:

Our DOM consists of different types of HTML elements. Generic HTML elements are of type HTMLElement. But we have many other types of HTML elements such as HTMLInputElement,  HTMLCanvasElement.  When we try to access an element from the component by using document.getElementById, by default TypeScript assumes that we are trying to access a document element which is of type HTMLElement and getContext property will not be available on this type of element.

Solution for Property ‘getContext’ does not exist on type ‘HTMLElement’ error in Angular 12 & TypeScript

The solution for this problem is, we need to tell TypeScript that the type of element we are trying to access is of HTMLCanvasElement type and not HTMLElement. We can do it in couple of ways


Copy to Clipboard

The same type of problem can occur not only in Angular applications, but also in any other framework such as React JS which is using strict TypeScript.