在Angular 2中如何检查< ng-content>是空的? [英] In Angular 2 how to check whether <ng-content> is empty?
本文介绍了在Angular 2中如何检查< ng-content>是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个组件:
@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 {
}
现在,如果此组件的< ng-content>
为空,我想显示一些默认内容。有没有一种简单的方法可以直接访问DOM?
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?
推荐答案
包裹 ng-content
在HTML元素(如 div
)中获取本地引用,然后绑定 ngIf
表达式 ref.children.length == 0
:
Wrap ng-content
in an HTML element like a div
to get a local reference to it, then bind the ngIf
expression to ref.children.length == 0
:
template: `<div #ref><ng-content></ng-content></div>
<span *ngIf="ref.nativeElement.childNodes.length == 0">
Display this if ng-content is empty!
</span>`
这篇关于在Angular 2中如何检查< ng-content>是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文