2017-11-20 6 views
1

こんにちは私はng-コンテンツの のいくつかの条件付き実装をしたいと思います。角度4/5の条件付きng-コンテンツ

<div> 
    <ng-content select="[card-icon]"></ng-content> 
</div> 
<div #body> 
    <div *ngIf="description.children.length;else newDiv"> 
     <ng-content select="[card-body]"></ng-content> 
    </div> 
    <div #newDiv> 
     <ng-content select="[card-body]"></ng-content> 
    </div> 
</div> 
<div style="align-self: end;" #description [ngClass]="{'hide':!(description.children.length)}"> 
<ng-content select="[card-description]" ></ng-content> 
</div> 

#newDivには何も投影されません。 TIA。

答えて

2

を使用します:

<div *ngIf=description.children.length> 
    <ng-container *ngTemplateOutlet="tempOutlet" ></ng-container> 
</div> 
<div *ngIf=!description.children.length> 
    <ng-container *ngTemplateOutlet="tempOutlet" ></ng-container> 
</div> 
<ng-template #tempOutlet> 
    <ng-content select="[card-body]"></ng-content> 
</ng-template> 

説明は:あなたは、同じ種類の複数のNG-コンテンツを持っている場合、これは(理由は例えばカードを行われています-body、カードアイコン、または空白の場合)、テンプレートの最後のコンテンツがHTMLに追加されます。したがって、単一のコンテンツを持ち、ng-templateとtemplate outletを使用して複数の位置に投影します。

1

より良いあなたが与えられたスニペットを使用することができますng-template

<div *ngIf="description.children.length;else newDiv"> 
     <ng-content select="[card-body]"></ng-content> 
     <ng-container *ngTemplateOutlet="newDiv"></ng-container> 
    </div> 

    <ng-template #newDiv> 
     <ng-content select="[card-body]"></ng-content> 
    </ng-template> 
+0

なぜですか?説明してくれますか? –

+0

@VivekDoshiこれはあなたの疑問をクリアするはずですhttps://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ –

+0

何も起こらない@RahulSingh私はは1か所にのみ表示する必要があります。つまり、重複しないようにしてください –

関連する問題