0
0
AngularConceptBeginner · 4 min read

What is ContentChild in Angular: Simple Explanation and Example

ContentChild in Angular is a decorator that lets a component access a single child element or directive projected into it from its parent. It helps you interact with content placed inside your component's tags using ng-content.
⚙️

How It Works

Imagine you have a box (a component) and you want to see or use something that someone puts inside that box (content projected from outside). ContentChild is like a special label inside the box that points to that specific item inside.

When Angular builds your component, it looks for the content placed inside your component's tags and matches it with the ContentChild selector. Then it gives you a reference to that content so you can read or change it.

This is different from ViewChild, which looks inside the component's own template. ContentChild looks at what is projected inside from outside.

💻

Example

This example shows a parent component projecting a button into a child component. The child uses ContentChild to get the button and change its text.

typescript
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: `<ng-content></ng-content>`
})
export class ChildComponent implements AfterContentInit {
  @ContentChild('projectedButton') button!: ElementRef<HTMLButtonElement>;

  ngAfterContentInit() {
    this.button.nativeElement.textContent = 'Clicked!';
  }
}

@Component({
  selector: 'app-root',
  template: `
    <child-comp>
      <button #projectedButton>Click me</button>
    </child-comp>
  `
})
export class AppComponent {}
Output
A button inside the child component changes its text from 'Click me' to 'Clicked!' after content initialization.
🎯

When to Use

Use ContentChild when you want your component to interact with or control a specific element or directive that is passed into it from outside via content projection (ng-content).

For example, if you build a wrapper component that styles or modifies buttons or inputs given by the user, ContentChild lets you access those elements directly.

It is helpful in creating reusable components that can work with dynamic content provided by their parent components.

Key Points

  • ContentChild accesses projected content inside a component.
  • It works with a single element or directive.
  • Use it with ng-content projection.
  • It differs from ViewChild, which accesses template elements.
  • Access is available after ngAfterContentInit lifecycle hook.

Key Takeaways

ContentChild lets a component access one projected child element or directive.
It is used with ng-content to interact with content passed from outside.
Access the content inside ngAfterContentInit lifecycle hook.
It differs from ViewChild, which accesses internal template elements.
Use ContentChild to build flexible, reusable components that work with dynamic content.