Back to course

Using Local Reference Variables for interaction

The Complete Angular Developer: From Zero to Hero

67. Using Local Reference Variables for interaction

We previously saw local reference variables (#input) referencing DOM elements. They can also be used to directly reference child component instances within the parent's template, allowing the parent to call public methods on the child.

Scenario: Parent Calling Child Method

Imagine a VideoPlayerComponent (child) needs a public play() method that the VideoDashboardComponent (parent) wants to trigger via a button.

1. Define Public Method in Child

typescript // video-player.component.ts (Child) export class VideoPlayerComponent { isPlaying: boolean = false;

play(): void { this.isPlaying = true; console.log('Video playing...'); } }

2. Define Reference and Call Method in Parent Template

The parent template assigns a reference variable to the child component tag, gaining access to the component instance.

html

<app-video-player #player>

<button (click)="player.play()"> Start Video

Video Status: Running

When to Use This Pattern?

This method is efficient for calling simple imperative actions on the child (e.g., reset(), focus(), open()). For passing data or complex state management, @Input/@Output or Services are still preferred.