是否可以在角度2+中进行条件内容投影(包含) [英] Is it possible to do conditional content projection (transclusion) in angular 2+
问题描述
我想提供默认内容,该内容仅在不包含内容的情况下才会显示.
I would like to provide default content that would appear only if content is not transcluded.
例如,这是我的组件模板:
For example Here is my component template:
<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
中的内容?
Now what if i wanted to provide a default header. Is it possible; without acrobatics like checking for content in ngAfterContentInit
?
推荐答案
您可以使用纯CSS做到这一点! 假设您有以下内容
You can do this with pure CSS! Imagine you have the following
<ng-content select=".header"></ng-content>
<h1 class="default-header">
This is my default header
</h1>
然后,如果提供了内容,则以下CSS将隐藏标题:
then the following CSS would hide the header if the content is supplied:
.header + .default-header {
display: none;
}
如果未提供标题,则显示:无规则不匹配.
If no header is supplied, then the display:none rule isn't matched.
请注意,您必须关闭内容封装才能使用此功能:encapsulation: ViewEncapsulation.None
Note, you'll have to turn off content encapsulation to use this: encapsulation: ViewEncapsulation.None
这篇关于是否可以在角度2+中进行条件内容投影(包含)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!