在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中的第一个元素并进行操作。