Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ NgTemplateOutlet inside ngFor

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>
like image 350
sevic Avatar asked Aug 22 '18 08:08

sevic


1 Answers

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"

like image 142
Julien METRAL Avatar answered Sep 27 '22 20:09

Julien METRAL