Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing for variable to ng-content

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>
like image 385
TKDev Avatar asked Aug 12 '18 08:08

TKDev


1 Answers

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>
like image 191
hgiasac Avatar answered Sep 18 '22 21:09

hgiasac