Angular viewChild vs ContentChild

Angular provides multiple decorators to access child components, directives, and DOM elements.
Two commonly used are:

  1. ViewChild
  2. ContentChild

What is ViewChild in Angular?

ViewChild is used to access:

  1. A DOM element inside the component’s template
  2. A child component inside the template
  3. A directive placed inside the template
  4. A template reference variable

Note: ViewChild works inside the component’s own HTML template.

Example: Access DOM Element with ViewChild


<!-- parent.component.html -->
<div #titleRef>Welcome to Angular</div>
<button (click)="changeTitle()">Change Title</button>

parent.component.ts


// parent.component.ts
@ViewChild('titleRef') title!: ElementRef;

changeTitle() {
  this.title.nativeElement.innerText = "Welcome To TechFliez!";
}

Access Child Component with ViewChild


@ViewChild(ChildComponent) child!: ChildComponent;

ngAfterViewInit() {
  this.child.printMessage();
}

What is ContentChild in Angular?

It is used to access

  1. Projected content passed from parent component
  2. ng-content inserted elements
  3. Template reference variables inside ng-content

Example: Using ContentChild to Access Projected Content

parent component template


<app-car>
  <h2 #header>Title From Parent</h2>
</app-car>

child component template


<div class="car">
  <ng-content></ng-content>
</div>

child component (ts file)


@ContentChild('header') headerRef!: ElementRef;

ngAfterContentInit() {
  console.log(this.headerRef.nativeElement.innerText);
}

Note: This will read the text “Title From Parent”.

ViewChild vs ContentChild – Key Differences

Feature ViewChild ContentChild
Works on Elements/directives inside component template Elements/directives projected via ng-content
Access Location View (component HTML) Content projected by parent
Lifecycle Hook ngAfterViewInit() ngAfterContentInit()
Use Case Access DOM, directives, child components Access projected content inside ng-content
Updates? Updates when view changes Updates when projected content changes