在Angular 4中动态加载图表组件?

时间:2017-08-03 03:40:06

标签: angular

我在Angular 4中创建了许多可重用的图表组件。所有绘制图表的数据都来自REST API。当我加载父组件时,我将以下列格式获取图表列表的数据。

[
   {
      "chartId":1,
      "chartType":"Bar"
   },
   {
      "chartId":2,
      "chartType":"Pie"
   }
]

我正在使用图表组件的属性选择器。例如,

<div app-bar-chart></div>

我想要做的是,我需要遍历图表列表JSON,并根据'chartType'我需要设置属性。例如,如果'chartType'是'Pie',则元素应为

<div app-pie-chart></div>

我该如何实现?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以设置属性,但不会在那里启动组件。

以下是如何做到这一点。创建一个包含对组件类的引用的JSON,而不是字符串:

export class BarComponent {...}
export class PieComponent {...}

...

const components = [
    {
        "chartId": 1,
        "chartType": BarComponent < ---component class reference
    },
    {
        "chartId": 2,
        "chartType": PieComponent
    }
]

然后使用NgComponentOutlet呈现这些组件:

<ng-container *ngFor="let c of components">
     <ng-container *ngComponentOutlet="c"></ng-container>

阅读这些文章以获取更多信息: