conditional ng-content in angular 4/5
Asked Answered
R

2

16

Hi I want some conditional implementation of ng-content e.g.

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

but nothing is projected in the #newDiv. TIA.

Ruthenian answered 20/11, 2017 at 6:32 Comment(0)
M
43

You can use given snippet:

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

Explanation: This is done because if you have multiple ng-content of same types (e.g. card-body, card-icon or blank) then the last ng-content in your template will be added to your HTML. So have a single ng-content and make it project into multiple positions using ng-template and template outlet.

Mcfall answered 20/11, 2017 at 7:20 Comment(1)
not working for me and I have actually found an issue here #51948801File
A
5

Better make use of 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>
Acinaciform answered 20/11, 2017 at 6:38 Comment(3)
Why ? will you please explain ?Boyish
@VivekDoshi this will clear your doubts i hope blog.angular-university.io/…Acinaciform
nothing happen @RahulSingh i think <ng-content select="[card-body]"></ng-content> should be at single place only i.e. should not be duplicatedRuthenian

© 2022 - 2024 — McMap. All rights reserved.