Reputation: 1052
I have created a number of reusable chart components in Angular 4. All the data to draw a chart coming from a REST api. When I am loading the parent component I will get the data for the list of charts in the following format.
[
{
"chartId":1,
"chartType":"Bar"
},
{
"chartId":2,
"chartType":"Pie"
}
]
I am using attribute selector for the chart components. For example,
<div app-bar-chart></div>
What I want to do is, I need to iterate through the chart list JSON and according to the 'chartType' I need to set the attribute. For example if 'chartType' is 'Pie' then the element should be,
<div app-pie-chart></div>
How can I implement this? Thank you.
Upvotes: 0
Views: 892
Reputation: 105439
You can set the attribute but you will not get the component initiated there.
Here is how you can do it. Create a JSON that contains the reference to the component class, not the string:
export class BarComponent {...}
export class PieComponent {...}
...
const components = [
{
"chartId": 1,
"chartType": BarComponent < ---component class reference
},
{
"chartId": 2,
"chartType": PieComponent
}
]
Then use NgComponentOutlet to render these components:
<ng-container *ngFor="let c of components">
<ng-container *ngComponentOutlet="c"></ng-container>
Read these articles for more information:
Upvotes: 0