2016-12-11 1 views
1

「カード」コンポーネントのコンシューマに(カードではなくコードを使用して)通信する方法があります。と 'card-footer'を含める必要がありますか?角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".'; 
    } 
    } 
} 

ない子どもたちは、そのセレクタに一致する渡された<ng-content>要素のためのヒントをeventuallyprovideかもしれない進行中のいくつかの言語サービス作業があります。

0

、あなたは条件付きでCardComponentの内側に投影HTMLを表示したいです。この場合、*ngIfを使用できます。たとえば、あなたはあなたのCardComponentにブール変数(または@Inputのparam)を宣言することができます。

次に、あなたがこれを行うテンプレートで:

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

CardComponentの親は、以下を持っているでしょうそのテンプレートで:showFooterfalseある場合

<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> 

CardComponentはRENません。フッタをder。

親の投影されたコンテンツをCardComponentに制御する場合は、親に同様のロジックを実装します。

関連する問題