Декоратор ContentChild
Что он делает
Настраивает запрос к содержимому.
Как использовать
.
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
}
}
Описание
Вы можете использовать ContentChild, чтобы получить первый элемент или директиву, соответствующую селектору, из DOM содержимого. Если содержимое DOM изменяется, и новый дочерний элемент соответствует селектору, свойство будет обновлено.
Запросы к содержимому задаются до вызова обратного вызова ngAfterContentInit.
Свойства метаданных:
- selector - тип директивы или имя, используемое для запроса.
- read - прочитать другой токен из запрошенного элемента.
Давайте рассмотрим пример:
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: @angular/core
экспортировано из @angular/core/index, определено в @angular/core/src/metadata/di.ts
© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v2.angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html