Angular: TypeError: Cannot read properties of undefined (reading 'nativeElement') — @ViewChild used in ngOnInit
A @ViewChild / viewChild() reference is undefined because the view is not created yet, or the element sits inside @if / *ngIf.
TypeError: Cannot read properties of undefined (reading 'nativeElement')Cannot read property 'nativeElement' of undefinedViewChild undefinedViewChild is undefined in ngOnInitCannot read properties of undefined (reading 'focus') Meaning
View queries are resolved after the view initialises. In ngOnInit they are undefined (unless { static: true } and the element is not inside a conditional). Use ngAfterViewInit, or afterNextRender, and remember elements inside @if exist only when the condition is true.
Common causes
- Using the query in
ngOnInitor the constructor - Element inside
*ngIf/@if/@forso the query is empty until rendered - Wrong template reference name (
#canvasvs 'canvasRef') { static: true }on an element inside a conditional- Component used before its view is created
⚡ Quick fix
- Use
ngAfterViewInit()orafterNextRender() - Use
{ static: true }only for elements that are always in the template - With signals use
viewChild('ref')and read it insideeffect/after render
Detailed fix by platform
Angular
@ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>; ngAfterViewInit() { const ctx = this.canvas.nativeElement.getContext('2d'); }
Code examples
Safe access
@ViewChild('canvas') canvas?: ElementRef<HTMLCanvasElement>;
ngAfterViewInit() {
const el = this.canvas?.nativeElement;
if (!el) return; // not rendered (e.g. inside an @if)
el.getContext('2d')?.fillRect(0, 0, 10, 10);
}How to diagnose
- Hook — ngOnInit or ngAfterViewInit?
- Condition — Element inside @if/ngIf?
- Reference — Does #name match the query?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- addEventListener on null TypeError: Cannot read properties of null (reading 'addEventListener')
- Cannot find control with name Angular: Error: Cannot find control with name: 'email' (reactive forms)
- exceeded maximum budget Angular build: Error: bundle initial exceeded maximum budget. Budget 1.00 MB was not met by 120.00 kB with a total of 1.12 MB
Most viewed in Angular
Other ways to find it
Where this error sits
Origin: On your device. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 15 Oct 2026