17

How do I pass an ngFor variable to the ng-content template.

Example, the containing-component:

<ul>
    <li *ngFor="let item of itemsArray">
       <ng-content></ng-content>
    </li>
</ul>

The nested content-component:

<div>
    <span *ngIf="item.type_one"></span>
    <span *ngIf="item.type_two"></span>
</div>

Example, both:

<containing-component>
    <content-component>
    </content-component>
</containing-component>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TKDev
  • 493
  • 1
  • 4
  • 19

1 Answers1

22

You can not use ng-content as dynamic template. Use ng-template instead

<ul>
    <li *ngFor="let item of itemsArray">
       <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item  }">
       </ng-container>
    </li>
</ul>
export class ContainingComponent {

  ...

  @ContentChild(TemplateRef, {static: true}) 
  @Input() itemTemplate: TemplateRef<any>;
}

So you can reference dynamic template into containing-component. In this case, you can wrap ng-template over content-component

<containing-component [itemTemplate]="itemTmpl">
</containing-component>

<ng-template #itemTmpl let-data>

    <content-component
      [item]="data">
    </content-component>
</ng-template>

Or use ng-template directly:

<containing-component 
   [itemTemplate]="itemTmpl"
   [itemArray]="items">
</containing-component>

<ng-template #itemTmpl let-data>
  <div>
    <span *ngIf="data.type_one"></span>
    <span *ngIf="data.type_two"></span>
  </div>
</ng-template>
KyleK
  • 4,643
  • 17
  • 33
hgiasac
  • 2,183
  • 16
  • 14
  • 1
    There is no `@ContentChild(TemplateRef) ` here . I had to set the ref to the name id of the template - https://i.imgur.com/zO15JIo.jpg. Is it possible not to reference it to the html variable , but to a TS variable instead ? https://stackblitz.com/edit/angular-rbubtu?file=src/app/app.component.html – Royi Namir Aug 12 '18 at 15:53
  • Like this. https://stackblitz.com/edit/angular-ny3blx?file=src/app/app.component.html. You are mistaking my idea – hgiasac Aug 12 '18 at 16:58
  • 2
    You can remove @contentchild . You're not using here any content as an ngcontent. Try and see :) – Royi Namir Aug 12 '18 at 17:01