'ViewChild element not working as expected

So actually what I want to do is simple I need to reference a canvas element from template in the typescript file

The code I use is @ViewChild('myCanvas', { static: true }) myCanvas: ElementRef<HTMLCanvasElement>; But it shows an error saying the variable has no initializer and is not definitely assigned in the constructor.

And if I add "!" or ":any" my below code won't work What I meant by my code "won't" work isn't that ngcc will signal a compilation error But instead what I want to do below needs the variable to be different from null or undefined or any

I ask because I once used the above code in another Angular Version and it worked fine Now I'm using Angular 13



Solution 1:[1]


@ViewChild('myCanvas', { static: true }) myCanvas!: ElementRef<HTMLCanvasElement>;

This one will "force" the compiler to accept that this variable is defined.


@ViewChild('myCanvas', { static: true }) myCanvas: any;

This one will remove the typing on your variable, effectively removing the intellisense of your IDE too.

But both of them should work. If they don't, please reproduce the issue on stackblitz.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 temp_user