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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With