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

ContentChild

用於配置內容查詢的引數裝飾器。

Parameter decorator that configures a content query.

檢視"說明"...

說明

用於從內容 DOM 獲取與此選擇器匹配的第一個元素或指令。如果內容 DOM 發生了更改,並且有一個新的子項與選擇器匹配,則該屬性將被更新。

Use to get the first element or the directive matching the selector from the content DOM. If the content DOM changes, and a new child matches the selector, the property will be updated.

在呼叫 ngAfterContentInit 之前設定的內容查詢。

Content queries are set before the ngAfterContentInit callback is called.

不檢索其他元件範本中的元素或指令,因為元件範本對其祖先來說始終是黑匣子。

Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors.

元資料屬性

Metadata Properties:

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

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

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

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

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

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

Further information available in the Usage Notes...

選項

使用說明

      
      import {AfterContentInit, ContentChild, Directive} from '@angular/core';

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

@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
  @ContentChild(ChildDirective) contentChild!: ChildDirective;

  ngAfterContentInit() {
    // contentChild is set
  }
}
    

Example

      
      import {Component, ContentChild, Directive, Input} from '@angular/core';

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

@Component({
  selector: 'tab',
  template: `
    <div>pane: {{pane?.id}}</div>
  `
})
export class Tab {
  @ContentChild(Pane) pane!: Pane;
}

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

    <button (click)="toggle()">Toggle</button>
  `,
})
export class ContentChildComp {
  shouldShow = true;

  toggle() {
    this.shouldShow = !this.shouldShow;
  }
}