【问题标题】:Is it possible to do conditional content projection (transclusion) in angular 2+是否可以在角度 2+ 中进行条件内容投影(嵌入)
【发布时间】:2017-01-24 15:37:38
【问题描述】:

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

例如这是我的组件模板:

<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中的内容?

【问题讨论】:

  • 看看这个答案stackoverflow.com/a/38692980/373655。不确定是否存在不需要ngAfterContentInit 的更优雅的解决方案
  • 另外,你能给投影起别名吗? &lt;ng-content class=".for-parent" select=".for-me"&gt;

标签: angular


【解决方案1】:

你可以用纯 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

【讨论】:

  • 聪明,出于某种原因,我从没想过兄弟选择器。 (也许我太老了?)
【解决方案2】:

有可能。

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

欲了解更多信息https://angular.io/guide/content-projection#conditional-content-projection

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2020-08-19
    • 2017-10-14
    • 2018-01-26
    相关资源
    最近更新 更多