是否可以将默认值设置为<ng-content>[重复]

问题描述 投票:0回答:3

我刚刚从本教程中学习了

Transluction
angular2
的使用:

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

我可以对某些内容使用

<ng-content>
标签,例如:

<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>

问题是:

是否可以将默认值添加到

<ng-content>
块中,如果我们没有传递任何值,则可以使用该默认值?

目前如果没有传递任何值,其位置将会出现空白页。

编辑:

当我尝试测试时,有较新版本的

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.

因此,它确认不能将任何默认值设置为

<ng-content>

angular default-value angular2-ngcontent
3个回答
20
投票

从角度 10 开始,以下作品:

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

它只是意味着,如果您的

ng-content
(参考)没有任何子节点(这意味着它是空的),则渲染具有“默认内容”的
ng-container


7
投票

只需使用:

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

-8
投票

如果您在

<ng-content>
标签内添加一些标记会怎样?

<ng-content select="[my-block-header]">
  <p>Some default markup here</p>
</ng-content>
© www.soinside.com 2019 - 2024. All rights reserved.