W3cubDocs

/Angular

ViewChild

decorator

Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

See more...

Description

View queries are set before the ngAfterViewInit callback is called.

Metadata Properties:

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

When static is not provided, uses 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.

The following selectors are supported.

  • Any class with the @Component or @Directive decorator
  • A template reference variable as a string (e.g. query <my-component #cmp></my-component> with @ViewChild('cmp'))
  • Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
  • Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)
  • A TemplateRef (e.g. query <ng-template></ng-template> with @ViewChild(TemplateRef) template;)

Options

Usage notes

import {Component, Directive, Input, ViewChild} from '@angular/core';

@Directive({selector: 'pane'})
export class Pane {
  @Input() id !: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>

    <button (click)="toggle()">Toggle</button>

    <div>Selected: {{selectedPane}}</div>
  `,
})
export class ViewChildComp {
  @ViewChild(Pane, {static: false})
  set pane(v: Pane) {
    setTimeout(() => { this.selectedPane = v.id; }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() { this.shouldShow = !this.shouldShow; }
}

Example 2

import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';

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

@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
  @ViewChild(ChildDirective, {static: false}) child !: ChildDirective;

  ngAfterViewInit() {
    // child is set
  }
}

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