What is the difference between ContentChild and ViewChild?

ContentChild and ViewChild are both decorators in Angular that allow you to access child elements of a component. The main difference between them is the timing of when they retrieve the child element.

  1. ContentChild: The ContentChild decorator retrieves a child element that was included in the component’s content, either as a transcluded content or as a content projection. The ContentChild decorator allows you to access the child element after the component’s content has been fully processed and after Angular has finished checking the component’s view for changes.
  2. ViewChild: The ViewChild decorator retrieves a child element from the component’s view. The ViewChild decorator allows you to access the child element after Angular has finished checking the component’s view for changes.

Here’s an example to demonstrate the difference between ContentChild and ViewChild :

// child.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    Child Component
  `,
})
export class ChildComponent {}

// parent.component.ts
import { Component, ContentChild, ViewChild, AfterContentInit, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <ng-content></ng-content>
    <app-child></app-child>
  `,
})
export class ParentComponent implements AfterContentInit, AfterViewInit {
  @ContentChild(ChildComponent, { static: false }) contentChild: ChildComponent;
  @ViewChild(ChildComponent, { static: false }) viewChild: ChildComponent;

  ngAfterContentInit() {
    console.log('ContentChild:', this.contentChild);
  }

  ngAfterViewInit() {
    console.log('ViewChild:', this.viewChild);
  }
}

In this example, the ParentComponent has both a ContentChild and a ViewChild. The ChildComponent is included in the parent component’s content and in its view. If you run this code, you’ll see that the ContentChild is available after ngAfterContentInit has been called, and the ViewChild is available after ngAfterViewInit has been called.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *