填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写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;
  }
}