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.
View queries are set before the ngAfterViewInit
callback is called.
Metadata Properties:
The following selectors are supported.
@Component
or @Directive
decorator<my-component #cmp></my-component>
with @ViewChild('cmp')
)@ViewChild(SomeService) someService: SomeService
)@ViewChild('someToken') someTokenVal: any
)TemplateRef
(e.g. query <ng-template></ng-template>
with @ViewChild(TemplateRef) template;
)The following values are supported by read
:
@Component
or @Directive
decoratorselector
of this query{provide: 'token', useValue: 'val'}
)TemplateRef
, ElementRef
, and ViewContainerRef
Further information is available in the 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; } }
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–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/core/ViewChild