Content Child decorator

Overview

Angular's @ContentChild decorator is a powerful feature that allows you to access and manipulate content projected into a component. This capability is essentially for building flexible and reusable components that can work with dynamic content. In this chapter, we will explore the @ContentChild decorator in Angular, providing a comprehensive understanding of its uses, practical examples, and detailed explanations.

Understanding @ContentChild

@ContentChild is a TypeScript decorator used to query and access content that has been projected into a component via the <ng-content> directive. It enables you to interact with this projected content programmatically, making your component more versatile and dynamic.

Declaring @ContentChild

To use @ContentChild, you declare it as class property within your component. You specify the type of content you want to access and provide an optional selector to identify the specific content you are interested in. Here's a basic example:

Child Component (app-child.component.html):

<div >
 <ng-content></ng-content>
</div>

Parent Component (app-parent.component.html):

<app-child>
  <h1>Title</h1>
  <p>Some content to be accessed via @ContentChild</p>
</app-child>

Parent Component TypeScript (app-parent.component.ts):

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

@Component({
  selector: 'app-parent',
  template: '<app-child></app-child>',
})
export class ParentComponent {
  @ContentChild('contentParagraph') contentParagraph: ElementRef;
}