简体   繁体   中英

Load chart components dynamically in Angular 4?

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM