Декоратор ViewChildren
Что он делает
Настраивает запрос к представлению.
Как использовать
.
import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
@ViewChildren(ChildDirective) viewChildren: QueryList<ChildDirective>;
ngAfterViewInit() {
// viewChildren is set
}
}
Описание
Вы можете использовать ViewChildren для получения QueryList элементов или директив из DOM представления. Всякий раз, когда элемент дочерний добавляется, удаляется или перемещается, список запросов обновляется, и наблюдаемые изменения списка запросов излучают новое значение.
Запросы к представлению устанавливаются до вызова обратного вызова ngAfterViewInit.
Свойства метаданных:
- selector - тип директивы или имя, используемое для запроса.
- read - считывать другой токен из запрошенных элементов.
Давайте рассмотрим пример:
import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
<button (click)="show()">Show 3</button>
<div>panes: {{serializedPanes}}</div>
`,
})
export class ViewChildrenComp implements AfterViewInit {
@ViewChildren(Pane) panes: QueryList<Pane>;
serializedPanes: string = '';
shouldShow = false;
show() { this.shouldShow = true; }
ngAfterViewInit() {
this.calculateSerializedPanes();
this.panes.changes.subscribe((r) => { this.calculateSerializedPanes(); });
}
calculateSerializedPanes() {
setTimeout(() => { this.serializedPanes = this.panes.map(p => p.id).join(', '); }, 0);
}
}
пакет 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/ViewChildren-decorator.html