ViewChild
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.
Description
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.
Supported selectors include:
- 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;
)
Usage notes
- import {Component, Directive, Input, ViewChild} from '@angular/core';
-
- @Directive({selector: 'pane'})
- export class Pane {
- // TODO(issue/24571): remove '!'.
- @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)
- set pane(v: Pane) {
- setTimeout(() => { this.selectedPane = v.id; }, 0);
- }
- selectedPane: string = '';
- shouldShow = true;
- toggle() { this.shouldShow = !this.shouldShow; }
- }
Example
- import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';
-
- @Directive({selector: 'child-directive'})
- class ChildDirective {
- }
-
- @Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
- class SomeCmp implements AfterViewInit {
- // TODO(issue/24571): remove '!'.
- @ViewChild(ChildDirective) child !: ChildDirective;
-
- ngAfterViewInit() {
- // child is set
- }
- }
Example
- import {Component, Directive, Input, ViewChild} from '@angular/core';
-
- @Directive({selector: 'pane'})
- export class Pane {
- // TODO(issue/24571): remove '!'.
- @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)
- set pane(v: Pane) {
- setTimeout(() => { this.selectedPane = v.id; }, 0);
- }
- selectedPane: string = '';
- shouldShow = true;
- toggle() { this.shouldShow = !this.shouldShow; }
- }