2017-01-24 24 views
7

条件内容投影(包含)我想提供,如果内容没有transcluded,只会显示默认的内容。是否有可能做角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内容杂技?

+1

看看这个答案http://stackoverflow.com/a/38692980/373655。不知道一个更优雅的解决方案存在不要求'ngAfterContentInit' – rob

+0

另外,你能别名投影? '' – Cody

回答

3

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

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

那么如果内容提供以下CSS将隐藏标题:

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

如果没有头提供,则显示:无规则不匹配。

注意,你必须关闭内容封装到使用这个:encapsulation: ViewEncapsulation.None

+2

聪明,我从来不认为同胞选择出于某种原因的。 (也许我太老了学校?) – dovidweisz