10

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>
sevic
  • 879
  • 11
  • 36

1 Answers1

16

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"

Julien METRAL
  • 1,894
  • 13
  • 30
  • 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 /: – sevic Aug 22 '18 at 08:29
  • 1
    ah but still thanks to answer i found the solution! everything in the example from the question was fine but the template. wrong: `` correct: `` thanks! – sevic Aug 22 '18 at 08:38
  • Yeah sorry, the `[ngTemplateOutlet]` is used in the case of a `ngFor*` : `` – Julien METRAL Aug 22 '18 at 08:39