在 Angular 中,ContentChild 用于引用组件中某个特定内容投影的 DOM 元素。当需要在父组件中访问子组件的子元素时,可以使用 ContentChild。
在下面的示例中,有一个 tab 组件,其中包含一个“pane”元素:
@Component({
selector: 'app-tab',
template: `
{{ tab.tabTitle }}
`,
})
export class TabComponent {
// ...
@ContentChild('pane') pane!: ElementRef;
// ...
}
在这个例子中,“pane”是一个模板引用变量,用于引用组件模板中的一个元素。这个元素将被投影到 tab 组件中。
在父组件中,可以使用 ContentChild 引用 pane 元素,并在必要时访问它:
@Component({
selector: 'app-parent',
template: `
This is the content section of the tab.
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(TabComponent) tab!: TabComponent;
ngAfterViewInit() {
console.log(this.tab.pane.nativeElement.innerText);
}
}
在这个例子中,ParentComponent 包含一个 TabComponent ,并在模板中使用“pane”模板引用变量来创建“pane”元素。然后,使用 ViewChild 引用 TabComponent,然后在 ngAfterViewInit 中访问 pane 元素的 innerText 属性。
这就是 ContentChild 以及在此示例中“pane”的含义。