Вы можете повторять полученные данные в ngFor
.
Вот простая логика.В данном примере это тип данных, которые я использую:
[{
"name": "John",
"age": 30,
"role": "Actor"
},
{
"name": "Elys",
"age": 22,
"role": "The main one"
},
{
"name": "Jhon",
"age": 44,
"role": "a random role"
}
]
(поддельная) служба, которая извлекает данные:
import { Injectable} from '@angular/core';
@Injectable()
export class MainService{
private data = [{
"name": "John",
"age": 30,
"role": "Actor"
},
{
"name": "Elys",
"age": 22,
"role": "The main one"
},
{
"name": "Jhon",
"age": 44,
"role": "a random role"
}
]
constructor(){}
public getData(){
return this.data;
}
}
The main component:
import { Component } from '@angular/core';
import { ChildComponent } from './child.component'
import { MainService } from './main.service'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
data: any;
constructor(private service: MainService){
this.data = this.service.getData();
}
}
<h2>The list above is created dinamically
<hr>
<ng-container *ngFor="let item of data">
<child-cmp [data]="item"></child-cmp>
<br>
</ng-container>
дочерний компонент
import { Component, Input } from '@angular/core';
@Component({
selector: 'child-cmp',
templateUrl: './child.component.html'
})
export class ChildComponent {
@Input() data: any;
}
<div style="display: flex; flex-direction: row">
<span style="margin-right: 10px"> {{data.name}}</span>
<span style="margin-right: 10px"> {{data.age}}</span>
<span style="margin-right: 10px"> {{data.role}}</span>
</div>
Примечание Я использовал ng-container
для итерации, потому что angular не отображает ее.
Рабочий стекблиц: https://stackblitz.com/edit/angular-2svnpt