This is the archived documentation for Angular v5. Please visit angular.io to see documentation for the current version of Angular.

ContentChild

npm Package @angular/core
Module import { ContentChild } from '@angular/core';
Source core/src/metadata/di.ts

Configures a content query.

How To Use

      
      import {AfterContentInit, ContentChild, Directive} from '@angular/core';

@Directive({selector: 'child-directive'})
class ChildDirective {
}

@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
  @ContentChild(ChildDirective) contentChild: ChildDirective;

  ngAfterContentInit() {
    // contentChild is set
  }
}
    

Description

You can use ContentChild to get the first element or the directive matching the selector from the content DOM. If the content DOM changes, and a new child matches the selector, the property will be updated.

Content queries are set before the ngAfterContentInit callback is called.

Metadata Properties:

  • selector - the directive type or the name used for querying.
  • read - read a different token from the queried element.

Let's look at an example:

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

@Directive({selector: 'pane'})
export class Pane {
  @Input() id: string;
}

@Component({
  selector: 'tab',
  template: `
    <div>pane: {{pane?.id}}</div> 
  `
})
export class Tab {
  @ContentChild(Pane) pane: Pane;
}

@Component({
  selector: 'example-app',
  template: `
    <tab>
      <pane id="1" *ngIf="shouldShow"></pane>
      <pane id="2" *ngIf="!shouldShow"></pane>
    </tab>
    
    <button (click)="toggle()">Toggle</button>
  `,
})
export class ContentChildComp {
  shouldShow = true;

  toggle() { this.shouldShow = !this.shouldShow; }
}
    

npm package: @angular/core