W3cubDocs

/Angular

ContentChild

decorator

Parameter decorator that configures a content query.

See more...

Description

Use 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.

Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors.

Metadata Properties:

  • selector - The directive type or the name used for querying.
  • read - True to read a different token from the queried element.
  • static - True to resolve query results before change detection runs, false to resolve after change detection.

When static is not provided, uses the query results to determine the timing of query resolution. If any query results are inside a nested view (such as *ngIf), the query is resolved after change detection runs. Otherwise, it is resolved before change detection runs.

Options

Usage notes

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

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

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

  ngAfterContentInit() {
    // contentChild is set
  }
}

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, {static: false}) 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; }
}

© 2010–2019 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/core/ContentChild