Angular - Project different content with only one ng-content in an *ngFor

381 views Asked by At

I'd want the ngfor to use one child component per iteration :

Card component, <card> :

<div *ngFor="let item of items">
   <ng-content [value]="item">
   </ng-content>
</div>

Use of the card component :

<card>
   <child-comp1> Hello </child-comp1>
   <child-comp2> Goodbye </child-comp2>
   <child-comp3> See you </child-comp3>
   ...
</card>

Expected result :

<card>
   <child-comp1> Hello item1</child-comp1>
   <child-comp2> Goodbye item2</child-comp2>
   <child-comp3> See you item3</child-comp3>
   ...
</card>

Of course there should be as much child components as data in the ngFor array for it to work correctly.

EDIT : the above exemple doesn't represent the actual datas and components used, it is only here to illustrate and explain the question. There could be more or less than 3 child components and they are more complex than just displaying values.

1

There are 1 answers

0
david medel On

I will try to help you.

First of all I created a main class that will call all the card components. main.component.html

<div *ngFor="let item of items">
  <app-card [values]="item">
  </app-card>
</div>

main.component.ts you only need to have your data here, for instance:

items: string[][] = [['it1.1','it1.2','it1.3'],['it2.1','it2.2','it2.3'],['it3.1','it3.2','it3.3']];

and in your card component: card.component.html

<ul>
    <li>Hello {{values[0]}}</li>
    <li>Goodbye {{values[1]}}</li>
    <li>See you {{values[2]}}</li>
</ul>

card.component.ts (Import Input is required)

import { Component, OnInit, Input } from '@angular/core';
@Input() values: string[] = [];