在Angular 8中,可以通过使用@ContentChildren
装饰器和QueryList
来选择ng-content
的第一个元素。以下是一个示例:
在父组件的模板中,使用ng-content
来定义插入的内容:
First Element
Second Element
在子组件的模板中,使用ng-content
来插入内容,并在组件类中定义@ContentChildren
和ngAfterContentInit
:
import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent implements AfterContentInit {
@ContentChildren('div') divs: QueryList;
ngAfterContentInit() {
const firstElement = this.divs.first;
console.log(firstElement); // 输出第一个div元素
}
}
在子组件中,使用@ContentChildren('div')
来选择所有带有div
标签的元素,并存储在QueryList
中。在ngAfterContentInit
生命周期钩子中,通过this.divs.first
获取第一个元素。
这样,就可以选择ng-content
中的第一个元素并进行操作。