要检测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是一个生命周期钩子函数,当组件的内容初始化完成后被调用。