要检测ng-content
是否包含内容或存在,可以使用@ContentChild
装饰器来获取ng-content
元素的引用,并使用ElementRef
来检查其内容。
下面是一个示例代码:
import { Component, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-custom-component',
template: `
`
})
export class CustomComponent {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
if (this.content.nativeElement.innerHTML.trim().length > 0) {
console.log('ng-content contains content');
} else {
console.log('ng-content is empty');
}
}
}
在上面的代码中,我们使用@ContentChild
装饰器来获取ng-content
元素的引用,并将其指定为content
。然后,在ngAfterContentInit
方法中,我们使用ElementRef
来访问ng-content
元素,并使用innerHTML
属性来检查其内容。如果内容的长度大于0,则说明ng-content
包含内容,否则为空。
请注意,ngAfterContentInit
是一个生命周期钩子函数,当组件的内容初始化完成后被调用。