19

我只是从本教程中学习使用Transluctionin :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>

4

3 回答 3

7

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

<div #ref><ng-content></ng-content></div>
<ng-container *ngIf="!ref.hasChildNodes()">
   Default Content
</ng-container>
于 2021-02-04T18:47:22.800 回答
5

只需使用:

<ng-content #myBlockHeader select="[my-block-header]"></ng-content>
<div *ngIf="!myBlockHeader">Default Content</div>
于 2019-10-03T13:19:03.070 回答
-6

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

<ng-content select="[my-block-header]">
  <p>Some default markup here</p>
</ng-content>
于 2017-01-24T10:22:16.353 回答