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.

属性装饰器,用于配置一个视图查询。 变更检测器会在视图的 DOM 中查找能匹配上该选择器的第一个元素或指令。 如果视图的 DOM 发生了变化,出现了匹配该选择器的新的子节点,该属性就会被更新。

说明

View queries are set before the ngAfterViewInit callback is called.

在调用 NgAfterViewInit 回调函数之前就会设置这些视图查询。

Metadata Properties:

元数据属性

  • selector - the directive type or the name used for querying.

    selector - 用于查询的指令类型或名字。

  • read - read a different token from the queried elements.

    read - 从查询到的元素中读取另一个令牌。

选项

使用说明

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