What it does
Configures a content query.
How to use
.
import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
@ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;
ngAfterContentInit() {
// contentChildren is set
}
}
Description
You can use ContentChildren to get the QueryList
of elements or directives from the
content DOM. Any time a child element is added, removed, or moved, the query list will be
updated,
and the changes observable of the query list will emit a new value.
Content queries are set before the ngAfterContentInit
callback is called.
Metadata Properties:
- selector - the directive type or the name used for querying.
- descendants - include only direct children or all descendants.
- read - read a different token from the queried elements.
Let's look at an example:
import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'tab',
template: `
<div>panes: {{serializedPanes}}</div>
`
})
export class Tab {
@ContentChildren(Pane) panes: QueryList<Pane>;
get serializedPanes(): string { return this.panes ? this.panes.map(p => p.id).join(', ') : ''; }
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
</tab>
<button (click)="show()">Show 3</button>
`,
})
export class ContentChildrenComp {
shouldShow = false;
show() { this.shouldShow = true; }
}
npm package: @angular/core
exported from @angular/core/index defined in @angular/core/src/metadata/di.ts