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

时间:2017-01-24 10:17:01

标签: angular default-value angular2-ngcontent

我刚从本教程的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>

3 个答案:

答案 0 :(得分:4)

从 angular 10 开始,以下工作:

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

答案 1 :(得分:0)

只需使用:

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

答案 2 :(得分:-2)

如果您在<ng-content>代码中添加了一些标记怎么办?

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