W3cubDocs

/Angular 2

ViewChildren decorator

What it does

Configures a view query.

How to use

.

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
  }
}

Description

You can use ViewChildren to get the QueryList of elements or directives from the view 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.

View queries are set before the ngAfterViewInit callback is called.

Metadata Properties:

  • selector - the directive type or the name used for querying.
  • read - read a different token from the queried elements.

Let's look at an example:

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 package: @angular/core

exported from @angular/core/index defined in @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