W3cubDocs

/Angular 12

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 - Used to read a different token from the queried elements.
  • static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

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;)

The following values are supported by read:

  • Any class with the @Component or @Directive decorator
  • Any provider defined on the injector of the component that is matched by the selector of this query
  • Any provider defined through a string token (e.g. {provide: 'token', useValue: 'val'})
  • TemplateRef, ElementRef, and ViewContainerRef

Further information is available in the Usage Notes...

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)
  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) child!: ChildDirective;

  ngAfterViewInit() {
    // child is set
  }
}

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