如何检查 <ng-content> 是否为空? (到目前为止在 Angular 2 中)

新手上路,请多包涵

假设我有一个组件:

 @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 的简单方法?

原文由 Slawomir Dadas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 473
2 个回答

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.children.length">
              Display this if ng-content is empty!
           </span>`

针对 Angular 12 更新; 旧逻辑(“ ref.nativeElement.childNodes.length ”)给出错误,因为 nativeElementundefined 现在。

原文由 pixelbits 发布,翻译遵循 CC BY-SA 4.0 许可协议

编辑 2020 年 3 月 17 日

纯 CSS(2 个解决方案)

如果没有投影到 ng-content 中,则提供默认内容。

可能的选择器:

  1. :only-child 选择器。在这里看到这篇文章 ::only-child Selector

这个需要更少的代码/标记。自 IE 9 以来的支持: 我可以使用 :only-child

  1. :empty 选择器。进一步阅读。

来自 IE 9 的支持以及部分自 IE 78 以来的支持: https ://caniuse.com/#feat=css-sel3

HTML

 <div class="wrapper">
    <ng-content select="my-component"></ng-content>
</div>
<div class="default">
    This shows something default.
</div>

CSS

 .wrapper:not(:empty) + .default {
    display: none;
}


万一它不起作用

请注意,至少有一个空格被认为不是空的。 Angular 会删除空格,但以防万一:

 <div class="wrapper"><!--
    --><ng-content select="my-component"></ng-content><!--
--></div>

或者

<div class="wrapper"><ng-content select="my-component"></ng-content></div>

原文由 Stefan Rein 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题