Template Reference Variables & ViewChild

5 questions found

What is a template reference variable in Angular, and how do you use one?

Beginner
A template reference variable, created with a hash symbol directly in your template, gives you a way to refer to a DOM element or a component instance from elsewhere within that same template, such as reading an input's current value when a button is clicked.
<input #nameInput type="text" />
<button (click)="greet(nameInput.value)">Greet</button>
Real-world example A simple search form reads the current value typed into an input field directly through a template reference variable when a search button is clicked, without needing any two way binding for this specific interaction.

Common follow-ups: Can a template reference variable be used outside of the specific template it was declared in?;What does a template reference variable refer to when placed on a custom Angular component instead of a native element?

Data Binding;Components & Templates

What does the ViewChild decorator do, and how would you use it to access a child component from a parent's TypeScript code?

Intermediate
ViewChild lets a parent component get a direct reference to a child component or a DOM element within its own template, from inside the parent's TypeScript class, letting the parent call methods or read properties directly on that child.
@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child><button (click)="child.doSomething()">Trigger</button>`
})
export class ParentComponent {
  @ViewChild('child') child!: ChildComponent;

  ngAfterViewInit() {
    console.log(this.child);
  }
}
Real-world example A parent component directly calls a reset method on a child form component using ViewChild, letting it clear the form's fields from a button located outside the child component itself.

Common follow-ups: Why is ViewChild data only reliably available starting in the ngAfterViewInit lifecycle hook?;What is the difference between ViewChild and ViewChildren?

Lifecycle Hooks;Components & Templates

How does the newer signal based viewChild function differ from the traditional ViewChild decorator?

Intermediate
The viewChild function returns a signal instead of a plain property, letting you read the referenced element or component reactively, and it can be marked as required, causing a clear error if the referenced element is unexpectedly missing, rather than silently being undefined.
import { viewChild } from '@angular/core';

export class ParentComponent {
  child = viewChild.required(ChildComponent);

  ngAfterViewInit() {
    console.log(this.child()); // called as a function, since it is a signal
  }
}
Real-world example A parent component uses the newer signal based viewChild function to access a required child component, getting a clear, immediate error during development if that child component is ever accidentally removed from the template.

Common follow-ups: What specific benefit does marking a viewChild as required actually provide over the traditional decorator?;Can viewChild signals be combined with computed signals for derived values?

Angular Signals;Lifecycle Hooks

How would you use ViewChildren to get references to multiple instances of the same child component or element?

Advanced
ViewChildren returns a QueryList containing every matching element or component instance found in the parent's template, which you can iterate over like an array, and it automatically updates if the number of matching elements changes over time, such as items being added or removed from a list.
@ViewChildren(ItemComponent) items!: QueryList<ItemComponent>;

ngAfterViewInit() {
  this.items.forEach((item) => console.log(item));
  this.items.changes.subscribe(() => console.log('The list of items changed'));
}
Real-world example A form with a dynamic number of input components uses ViewChildren to loop through every current input instance and validate them all together, automatically staying in sync even as inputs are added or removed.

Common follow-ups: What does the changes observable on a QueryList actually emit, and when does it fire?;How does ViewChildren differ from ContentChildren?

Content Projection (ng-content);RxJS & Observables

What is the difference between ViewChild and ContentChild in Angular?

Beginner
ViewChild accesses an element or component that is part of a component's own template, defined directly by that component. ContentChild accesses an element or component that was projected into the component from outside, using content projection, meaning it comes from whatever content the parent using the component actually supplied.
// ViewChild, accesses something defined in this component's own template
@ViewChild('internalElement') internal!: ElementRef;

// ContentChild, accesses something projected in from outside via ng-content
@ContentChild('projectedElement') projected!: ElementRef;
Real-world example A custom card component uses ViewChild to reference its own internal header element, while using ContentChild to reference a specific piece of content that a parent using the card component chose to project inside it.

Common follow-ups: In which lifecycle hook does ContentChild data become reliably available?;Can a component use both ViewChild and ContentChild together for different purposes?

Content Projection (ng-content);Lifecycle Hooks