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

ViewChildren

用於配置檢視查詢的引數裝飾器。

Parameter decorator that configures a view query.

檢視"說明"...

說明

用於從檢視 DOM 中獲取元素或指令的 QueryList。每當新增、刪除或移動子元素時,此查詢列表都將更新,並且其可觀察物件 changes 將發出新值。

Use to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.

在呼叫 ngAfterViewInit 前設定的檢視查詢。

View queries are set before the ngAfterViewInit callback is called.

元資料屬性

Metadata Properties:

  • selector - 要查詢的指令型別或名稱。

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

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

  • read - 用於從查詢的元素中讀取不同的令牌。

    emitDistinctChangesOnly - The QueryList#changes observable will emit new values only if the QueryList result has changed. When false the changes observable might emit even if the QueryList has not changed. Note: * This config option is deprecated, it will be permanently set to true and removed in future versions of Angular.

Further information available in the Usage Notes...

選項

使用說明

      
      import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core';

@Directive({selector: 'child-directive'})
class ChildDirective {
}

@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
  @ViewChildren(ChildDirective) viewChildren!: QueryList<ChildDirective>;

  ngAfterViewInit() {
    // viewChildren is set
  }
}
    

Another example

      
      import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core';

@Directive({selector: 'pane'})
export class Pane {
  @Input() id!: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1"></pane>
    <pane id="2"></pane>
    <pane id="3" *ngIf="shouldShow"></pane>

    <button (click)="show()">Show 3</button>

    <div>panes: {{serializedPanes}}</div>
  `,
})
export class ViewChildrenComp implements AfterViewInit {
  @ViewChildren(Pane) panes!: QueryList<Pane>;
  serializedPanes: string = '';

  shouldShow = false;

  show() {
    this.shouldShow = true;
  }

  ngAfterViewInit() {
    this.calculateSerializedPanes();
    this.panes.changes.subscribe((r) => {
      this.calculateSerializedPanes();
    });
  }

  calculateSerializedPanes() {
    setTimeout(() => {
      this.serializedPanes = this.panes.map(p => p.id).join(', ');
    }, 0);
  }
}