如何检查<ng-content>是空的?(到目前为止,在 Angular 2+ 中) [英] How to check whether <ng-content> is empty? (in Angular 2+ till now)
问题描述
假设我有一个组件:
@Component({
selector: 'MyContainer',
template: `
<div class="container">
<!-- some html skipped -->
<ng-content></ng-content>
<span *ngIf="????">Display this if ng-content is empty!</span>
<!-- some html skipped -->
</div>`
})
export class MyContainer {
}
`})导出类 MyContainer {}
Now, I would like to display some default content if <ng-content>
for this component is empty. Is there an easy way to do this without accessing the DOM directly?
现在,如果此组件的
为空,我想显示一些默认内容.有没有一种简单的方法可以在不直接访问 DOM 的情况下做到这一点?
推荐答案
将 ng-content
包裹在一个 HTML 元素中,比如 div
以获得对它的本地引用,然后将 ngIf
表达式绑定到 ref.children.length == 0
:
template: `<div #ref><ng-content></ng-content></div>
<span *ngIf=" ! ref.children.length">
Display this if ng-content is empty!
</span>`
<块引用>
针对 Angular 12 更新; 旧逻辑(ref.nativeElement.childNodes.length
")给出错误,因为 nativeElement
是undefined
现在.
Updated for Angular 12; old logic ("
ref.nativeElement.childNodes.length
") gives error, asnativeElement
isundefined
nowadays.
这篇关于如何检查<ng-content>是空的?(到目前为止,在 Angular 2+ 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!