Angular 2+ NgTemplateOutlet inside ngFor
Asked Answered
L

1

11

We have some arrays like:

  • heroes: Hero[];
  • villains: Villain[];
  • ...
  • puppies: Puppy[]

and a template like

<p *ngFor="let individual of heroes">
    {{ individual.name }} - {{ individual.mobileNumber }}
    ...
</p>
    <p *ngFor="let individual of villains">
    {{ individual.name }} - {{ individual.mobileNumber }}
    ...
</p>
...
 <p *ngFor="let individual of puppies">
    {{ individual.name }} - {{ individual.mobileNumber }}
    ...
</p>

The *ngFor loops have all the same content. To simplify that we create one ng-template that we can reuse.

<ng-template let-individual #individualParagraphContent>
    {{ individual.name }} - {{ individual.mobileNumber }}
    ...
<ng-template>

Now we want to use it like e.g.:

<p *ngFor="let individual of puppies">
  <ng-content *ngTemplateOutlet="individualParagraphContent;
              context: {individual: individual}">
  </ng-content>
</p>

Here I failed. I found examples where the whole *ngFor loop is in the template and how to pass a value from the component itself, but i did not manage to insert a <ng-template> into a for loop and to pass the variable(individual) correct.

EDIT Solved. Everything was fine but the initialization in the ng-template

<ng-template let-individual="individual" #individualParagraphContent>
Lawman answered 22/8, 2018 at 8:0 Comment(0)
W
17

Try something like this :

<ng-container
    *ngFor="let individual of heroes"
    [ngTemplateOutlet]="individualParagraphContent"
    [ngTemplateOutletContext]="{individual: individual}"></ng-container>

and for the template :

<ng-template let-individual="individual" #individualParagraphContent>
    <p>
       {{ individual.name }} - {{ individual.mobileNumber }}
       ...
    </p>
<ng-template>

let-(x)="key for x in the context"

Waers answered 22/8, 2018 at 8:9 Comment(3)
thanks for ur answer! as soon as we use [ngTemplateOutlet]= instead of *ngTemplateOutlet= the template does not get rendered anymore it seems... i tried using ngTemplateOutletContext in different ways, but still i did not find the correct one /:Lawman
ah but still thanks to answer i found the solution! everything in the example from the question was fine but the template. wrong: <ng-template let-individual #individualParagraphContent> correct: <ng-template let-individual="individual" #individualParagraphContent> thanks!Lawman
Yeah sorry, the [ngTemplateOutlet] is used in the case of a ngFor* : <ng-container *ngFor="let individual of puppies" [ngTemplateOutlet]="individualParagraphContent" [ngTemplateOutletContext]="{ individual: individual }"></ng-container>Waers

© 2022 - 2024 — McMap. All rights reserved.