2016-12-11 35 views
1

鑑於下面的例子,是否有一種方法可以通過代碼,而不是文檔與'卡'組件的消費者進行通信:'card-header'和'card-footer'應該包括在內?Angular 2 Transclusion/ng-content,溝通依賴關係

示例組件:

import { Component, Input } from '@angular/core'; 

@Component({ 
    moduleId: module.id, 
    selector: 'card', 
    templateUrl: 'card.component.html', 
}) 
export class CardComponent { 
} 

例HTML(card.component.html):

<div class="card"> 
    <div class="card-header"> 
    <ng-content select="card-header"></ng-content> 
    </div> 

    <ng-content></ng-content> 

    <div class="card-footer"> 
    <ng-content select="card-footer"></ng-content> 
    </div> 
</div> 

回答

2

您可以查詢傳遞的內容並拋出異常。 目前無法在開發時通知用戶。

<div class="card"> 
    <div class="card-header" #header> 
    <ng-content select="card-header"></ng-content> 
    </div> 
    <div #body>  
    <ng-content></ng-content> 
    </body> 
    <div class="card-footer" #footer> 
    <ng-content select="card-footer"></ng-content> 
    </div> 
</div> 
@Component({ 
    moduleId: module.id, 
    selector: 'card', 
    templateUrl: 'card.component.html', 
}) 
export class CardComponent { 
    @ContentChildren('header') header:ElementRef; 
    @ContentChildren('body') body:ElementRef; 
    @ContentChildren('footer') header:ElementRef; 

    ngAfterContentInit() { 
    if(!this.header.toArray().length) { 
     throw 'No content was provided that matches ".card-header".'; 
    } 
    if(!this.body.toArray().length) { 
     throw 'No body content was provided.'; 
    } 
    if(!this.footer.toArray().length) { 
     throw 'No content was provided that matches ".card-footer".'; 
    } 
    } 
} 

有正在進行的一些語言服務的工作,可能eventuallyprovide暗示對於那些沒有孩子們通過滿足他們的選擇是<ng-content>元素。

0

如果我理解正確的話,你要有條件地顯示內部CardComponent投影HTML。在這種情況下,您可以使用*ngIf。例如,你可以在你的CardComponent聲明一個布爾變量(或@Input PARAM):然後在模板

你這樣做:

<div *ngIf="showFooter"> 
    <ng-content select="card-footer"></ng-content> 
    </div> 

CardComponent的父母將具有以下在它的模板:

<card> 
    <div class="card-header" ><i>Card got this header from parent</i></div> 
    <div class="card-footer"><i>Card got this footer from parent</i></div> 
    </card> 

如果showFooterfalse,該CardComponent不會仁在頁腳。

如果要控制CardComponent的父項中的投影內容,請在父項中實現類似的邏輯。