繁体   English   中英

是否可以在 angular 2+ 中进行条件内容投影(嵌入)

[英]Is it possible to do conditional content projection (transclusion) in angular 2+

我想提供仅在内容未被嵌入时才会出现的默认内容。

例如这是我的组件模板:

<article>
    <header>
        <ng-content select="[header]"></ng-content>
    </header>
    <section>
        <ng-content></ng-content>
    </section>
</article>

我可以这样使用它:

<my-component>
    <h1 header>This is my header</h1>
    <p>This is my content</p>
</my-component>

现在如果我想提供一个默认标题怎么办。 是否可以; 没有像检查ngAfterContentInit内容这样的杂技?

你可以用纯 CSS 做到这一点! 想象一下你有以下

<ng-content select=".header"></ng-content>
<h1 class="default-header">
     This is my default header
</h1>

如果提供了内容,则以下 CSS 将隐藏标题:

.header + .default-header {
    display: none;
}

如果未提供标题,则 display:none 规则不匹配。

请注意,您必须关闭内容封装才能使用此功能: encapsulation: ViewEncapsulation.None

有可能的。

您应该将该组件配置为接受一个 ng-template 元素,该元素包含您要有条件地呈现的内容。

有关更多信息https://angular.io/guide/content-projection#conditional-content-projection

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM