Help Angular by taking a 1 minute survey!Go to surveyHome

ContentChild

Configures a content query.

See more...

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.

Options

Usage notes

Example

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 } }
      
      
  1. import {AfterContentInit, ContentChild, Directive} from '@angular/core';
  2.  
  3. @Directive({selector: 'child-directive'})
  4. class ChildDirective {
  5. }
  6.  
  7. @Directive({selector: 'someDir'})
  8. class SomeDir implements AfterContentInit {
  9. @ContentChild(ChildDirective) contentChild !: ChildDirective;
  10.  
  11. ngAfterContentInit() {
  12. // contentChild is set
  13. }
  14. }

Example

import {Component, ContentChild, Directive, Input} from '@angular/core'; @Directive({selector: 'pane'}) export class Pane { // TODO(issue/24571): remove '!'. @Input() id !: string; } @Component({ selector: 'tab', template: ` <div>pane: {{pane?.id}}</div> ` }) export class Tab { // TODO(issue/24571): remove '!'. @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; } }
      
      
  1. import {Component, ContentChild, Directive, Input} from '@angular/core';
  2.  
  3. @Directive({selector: 'pane'})
  4. export class Pane {
  5. // TODO(issue/24571): remove '!'.
  6. @Input() id !: string;
  7. }
  8.  
  9. @Component({
  10. selector: 'tab',
  11. template: `
  12. <div>pane: {{pane?.id}}</div>
  13. `
  14. })
  15. export class Tab {
  16. // TODO(issue/24571): remove '!'.
  17. @ContentChild(Pane) pane !: Pane;
  18. }
  19.  
  20. @Component({
  21. selector: 'example-app',
  22. template: `
  23. <tab>
  24. <pane id="1" *ngIf="shouldShow"></pane>
  25. <pane id="2" *ngIf="!shouldShow"></pane>
  26. </tab>
  27. <button (click)="toggle()">Toggle</button>
  28. `,
  29. })
  30. export class ContentChildComp {
  31. shouldShow = true;
  32.  
  33. toggle() { this.shouldShow = !this.shouldShow; }
  34. }