# Angular: TypeError: Cannot read properties of undefined (reading 'nativeElement') — @ViewChild used in ngOnInit

**Code:** `ViewChild is undefined` · **Category:** Angular · **Seen on:** Angular, TypeScript

A `@ViewChild` / `viewChild()` reference is `undefined` because the view is not created yet, or the element sits inside `@if` / `*ngIf`.

## 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 `ngOnInit` or the constructor
- Element inside `*ngIf` / `@if` / `@for` so the query is empty until rendered
- Wrong template reference name (`#canvas` vs 'canvasRef')
- `{ static: true }` on an element inside a conditional
- Component used before its view is created

## Quick fix

1. Use `ngAfterViewInit()` or `afterNextRender()`
2. Use `{ static: true }` only for elements that are always in the template
3. With signals use `viewChild('ref')` and read it inside `effect`/after render

## Detailed fix by platform

### Angular

1. `@ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>; ngAfterViewInit() { const ctx = this.canvas.nativeElement.getContext('2d'); }`

## Code examples

### Safe access

```typescript
@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

1. **Hook** — ngOnInit or ngAfterViewInit?
2. **Condition** — Element inside @if/ngIf?
3. **Reference** — Does #name match the query?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/angular/viewchild-undefined-in-ngoninit)
