填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

ViewChild

屬性裝飾器,用於配置一個檢視查詢。 變更檢測器會在檢視的 DOM 中查詢能匹配上該選擇器的第一個元素或指令。 如果檢視的 DOM 發生了變化,出現了匹配該選擇器的新的子節點,該屬性就會被更新。

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.

檢視"說明"...

說明

在呼叫 NgAfterViewInit 回呼(Callback)函式之前就會設定這些檢視查詢。

View queries are set before the ngAfterViewInit callback is called.

元資料屬性

Metadata Properties:

  • selector - 用於查詢的指令型別或名字。

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

  • read - 從查詢到的元素中讀取另一個令牌。

    read - Used to read a different token from the queried elements.

  • static - 如果為 true,則在變更檢測執行之前解析查詢結果,如果為 false,則在變更檢測之後解析。預設為 false。

    static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

支援下列選擇器:

The following selectors are supported.

  • 任何帶有 @Component@Directive 裝飾器的類別

    Any class with the @Component or @Directive decorator

  • 字串形式的範本參考變數(比如可以使用 @ViewChild('cmp') 來查詢 <my-component #cmp></my-component>

    A template reference variable as a string (e.g. query <my-component #cmp></my-component> with @ViewChild('cmp'))

  • 元件樹中任何當前元件的子元件所定義的提供者(比如 @ViewChild(SomeService) someService: SomeService

    Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)

  • 任何透過字串令牌定義的提供者(比如 @ViewChild('someToken') someTokenVal: any

    Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)

  • TemplateRef(比如可以用 @ViewChild(TemplateRef) template; 來查詢 <ng-template></ng-template>

    A TemplateRef (e.g. query <ng-template></ng-template> with @ViewChild(TemplateRef) template;)

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

例子

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