Skip to the workspace
Pebellslearn by building
Components  ›  Capstone Project

ViewChild and ContentChild

ViewChild 15 minviewChild finds an element or component in a component's own template, while contentChild finds one that a parent projected into it through ng-content.

angular / ViewChild and ContentChild

Explore each scene at your own pace.

01 · The rule

The rule

ViewChild and ContentChild

When the "Add plant" form opens, the cursor should jump into the name box. That means the component's class needs a handle on an element in the template. Angular gives you two queries, and the right one depends on who wrote the element.

The rule

viewChild finds what I wrote; contentChild finds what I was given.

viewChild searches the component's own template. Mark the element with a template reference variable (#name) and query it:

import { Component, ElementRef, viewChild } from '@angular/core';

@Component({
  selector: 'app-add-plant',
  template: `<input #nameBox placeholder="Plant name" />
             <button (click)="focusName()">Start</button>`,
})
export class AddPlant {
  nameBox = viewChild<ElementRef<HTMLInputElement>>('nameBox');

  focusName() {
    this.nameBox()?.nativeElement.focus();
  }
}

The query returns a signal. It is undefined until Angular has built the view, hence ?.. Use viewChild.required(...) when the element is always present.

contentChild searches projected content: markup a parent places between your tags, which you display with <ng-content />.

@Component({
  selector: 'app-panel',
  template: `<section>
               <button #closeBtn>Close</button>
               <ng-content />
             </section>`,
})
export class Panel {
  title = contentChild<ElementRef>('panelTitle');
}
<app-panel>
  <h2 #panelTitle>Add a plant</h2>
</app-panel>

The <h2> was written in the parent's template, so from Panel's point of view it is content, not view.

You can query a component type too: viewChild(PlantCard) returns the PlantCard instance. For many matches use viewChildren and contentChildren, which return lists. Older code writes @ViewChild('nameBox') nameBox!: ElementRef; with the same meaning.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.