问题 如果ng-content有内容或空Angular2


我试图了解如何创建一个if何时显示 ng-content 是空的。

<div #contentWrapper [hidden]="isOpen">
    <ng-content ></ng-content>
</div>

<span *ngIf="contentWrapper.childNodes.length == 0">
    <p>Display this if ng-content is empty!</p>
</span>

当内容为空时,我尝试使用那个显示数据,但即使信息为空也没有显示 <span> 标签

谢谢,永远感谢你的帮助。


5112
2018-06-17 06:17


起源

看看我的解决方案: stackoverflow.com/a/49563380/1296298 - Lerner


答案:


使用 children 代替 childNodes。 Angular为其创建注释节点 *ngIf* which are counted bychildNodes`

<div #contentWrapper [hidden]="isOpen">
    <ng-content ></ng-content>
</div>

<span *ngIf="contentWrapper.children.length == 0">
    <p>Display this if ng-content is empty!</p>
</span>  

Plunker的例子


11
2018-06-17 06:25



谢谢Mate,你的答案会更好 - rodboc
我认为如果ngIf在包装器本身上,那将无效 - Ced
@Ced不,在这种情况下你必须使用类似的东西 @ViewChild('contentWrapper') wrapper:ElementRef; 和 *ngIf="wrapper?.nativeElement?.children?.length" - Günter Zöchbauer
@GünterZöchbauer似乎不起作用。我现在正在努力解决同样的问题:嵌入时从DOM中删除一个元素 <ng-content> 是空的。猜猜只能通过模板投影来解决,但是如何?尚未找到配方。 - willydee
对不起,不知道是什么问题。我建议您使用代码创建一个新问题,该代码显示如何重现以及您尝试完成的任务。 - Günter Zöchbauer