Angular ViewChild and ContentChild

Angular ViewChild and ContentChild

@ViewChild and @ContentChild let you access child components, directives, or DOM elements directly from the parent class.

@ViewChild — Access Template Elements

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

@Component({
  selector: 'app-search',
  standalone: true,
  template: `
    <input #searchInput type="text" />
    <app-dropdown #dropdown />
  `
})
export class SearchComponent implements AfterViewInit {
  @ViewChild('searchInput') searchInput!: ElementRef<HTMLInputElement>;
  @ViewChild('dropdown')    dropdown!: DropdownComponent;

  ngAfterViewInit(): void {
    // Safe to access after view initialises
    this.searchInput.nativeElement.focus();
  }

  openDropdown(): void {
    this.dropdown.open();
  }
}

@ViewChildren — Multiple Elements

import { ViewChildren, QueryList } from '@angular/core';

@ViewChildren('item') items!: QueryList<ElementRef>;

ngAfterViewInit(): void {
  this.items.forEach(item => console.log(item.nativeElement.textContent));

  // React to changes in the list
  this.items.changes.subscribe(() => {
    console.log('Items list changed');
  });
}

@ContentChild — Access Projected Content

// Card component with projected content
@Component({
  selector: 'app-card',
  template: `<div class="card"><ng-content /></div>`
})
export class CardComponent implements AfterContentInit {
  @ContentChild('header') header!: ElementRef;

  ngAfterContentInit(): void {
    console.log('Projected header:', this.header?.nativeElement.textContent);
  }
}