Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional ng-content in angular 4/5

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.

like image 238
Mantu Nigam Avatar asked Nov 20 '17 06:11

Mantu Nigam


2 Answers

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.

like image 167
Ankit Kapoor Avatar answered Nov 06 '22 09:11

Ankit Kapoor


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>
like image 4
Rahul Singh Avatar answered Nov 06 '22 11:11

Rahul Singh