2017-01-24 34 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