【问题标题】:Is it possible to set default value to <ng-content> [duplicate]是否可以将默认值设置为 <ng-content> [重复]
【发布时间】:2017-06-09 02:15:45
【问题描述】:

我刚刚从本教程中学习Transluctionangular2 中的用法:

https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

我可以将&lt;ng-content&gt; 标签用于某些内容,例如:

<ng-content select="[my-block-header]"></ng-content>

它位于附加my-block选择器的组件中。

它将我的其他组件中的内容呈现为:

<my-block>
    <div class="box-header" my-block-header> <--added the slot selector here
        <h3 class="box-title">
            My title
        </h3>
    </div>
</my-block>

问题是:

是否可以将默认值添加到 &lt;ng-content&gt; 块中,如果我们不传递任何值,可以使用该块?

就目前而言,如果没有传递任何值,它的位置就会出现空白页。

编辑:

当我尝试测试时,有较新版本的 zone.js 不允许显示正确的错误,因此我收到的错误如下:

Cannot set property 'stack' of undefined ; Zone: <root> ; 
Task: Promise.then ; Value: TypeError: Cannot set property 'stack' of undefined

但是当我将 zone.js 的版本更改为 0.7.2 时,控制台中清楚地提到了错误:

zone.js:392 Unhandled Promise rejection: Template parse errors:
<ng-content> element cannot have content.

因此,它确认不能将任何默认值设置为&lt;ng-content&gt;

【问题讨论】:

标签: angular default-value angular2-ngcontent


【解决方案1】:

从 Angular 10 开始,以下工作:

<div #ref><ng-content></ng-content></div>
<ng-container *ngIf="!ref.hasChildNodes()">
   Default Content
</ng-container>

【讨论】:

    【解决方案2】:

    只需使用:

    <ng-content #myBlockHeader select="[my-block-header]"></ng-content>
    <div *ngIf="!myBlockHeader">Default Content</div>
    

    【讨论】:

    【解决方案3】:

    如果您在&lt;ng-content&gt; 标签中添加一些标记会怎样?

    <ng-content select="[my-block-header]">
      <p>Some default markup here</p>
    </ng-content>
    

    【讨论】:

    • 它给我的错误是:Cannot set property 'stack' of undefined ; Zone: &lt;root&gt; ; Task: Promise.then ; Value: TypeError: Cannot set property 'stack' of undefined
    • 无赖。然后,我不知道该怎么做。
    • 我们无法在 上设置默认值。现在错误消息清楚地提到了它:&lt;ng-content&gt; element cannot have content.
    • 对于ViewEncapsulation.Native,您可以使用&lt;content&gt;&lt;slot&gt; 元素。 &lt;content&gt;支持默认内容,不知道&lt;slot&gt;Native 目前还没有得到很好的支持。尤其是样式可能会成为问题,因为 &gt;&gt;&gt;/deep/ 将不再起作用。
    • 有没有比使用&lt;content&gt; 更好的选择?我使用&lt;content&gt; 获得了默认值,但除非我使用ViewEncapsulation.Native,否则它不会让我覆盖,并且正如您之前所说,它也破坏了我的样式:(
    猜你喜欢
    • 2019-08-24
    • 2014-10-15
    • 2021-07-22
    • 2021-05-12
    • 1970-01-01
    • 2011-10-15
    • 2015-07-17
    • 2021-06-14
    • 2019-04-05
    相关资源
    最近更新 更多