LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1814 min read

Template Reference Variables & ViewChild

Get a direct reference to a DOM element or child component using template reference variables and the @ViewChild decorator.

Template Reference Variables

A hash-prefixed name on an element (#myRef) creates a local template reference variable, usable elsewhere in that same template — a lightweight way to access an element or its properties without touching the component class at all.

<input #nameInput placeholder="Your name" />
<button (click)="greet(nameInput.value)">Greet</button>

@ViewChild

For access from the component class itself — not just within the template — @ViewChild reads a template reference variable (or a component/directive type) into a class property.

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-search',
standalone: true,
template: `<input #searchInput />`,
})
export class SearchComponent implements AfterViewInit {
@ViewChild('searchInput') searchInput!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.searchInput.nativeElement.focus();
}
}
Only Available After ngAfterViewInit

A @ViewChild reference is undefined until Angular has finished initializing the view — always access it inside (or after) ngAfterViewInit, never in the constructor or ngOnInit.

Accessing a Child Component

@ViewChild can also target a child component type directly, giving access to its public properties and methods.

import { Component, ViewChild } from '@angular/core';
import { VideoPlayerComponent } from './video-player.component';
@Component({
selector: 'app-page',
standalone: true,
imports: [VideoPlayerComponent],
template: `
<app-video-player />
<button (click)="player.play()">Play</button>
`,
})
export class PageComponent {
@ViewChild(VideoPlayerComponent) player!: VideoPlayerComponent;
}

Common Beginner Mistakes

Using @ViewChild as a default way to read component state

This bypasses Angular's standard @Input/@Output communication model — reserve @ViewChild for genuine imperative needs (focusing an input, calling a method directly), not everyday data flow.

Accessing @ViewChild in the constructor

The view doesn't exist yet at that point — access it starting in ngAfterViewInit.

FAQs

@ViewChild queries elements in the component's own template; @ContentChild queries elements projected into it via ng-content from a parent.

Yes — modern Angular introduces a viewChild() signal-based query function, offering the same capability with signal-based reactivity, covered in the signals section.

Summary

Template reference variables give quick, template-local DOM access, while @ViewChild brings that same access into the component class for genuine imperative needs. With component fundamentals and communication covered, the next section introduces modern Angular's standalone components and Signals in depth.

Next Lesson →

Standalone Components