[英]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. 我在Angular 4中创建了许多可重用的图表组件。所有用于绘制图表的数据均来自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. 我想做的是,我需要遍历图表列表JSON,然后根据“ chartType”设置属性。 For example if 'chartType' is 'Pie' then the element should be,
例如,如果“ chartType”为“ Pie”,则元素应为,
<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:
创建一个JSON,其中包含对组件类的引用,而不是字符串:
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: 然后使用NgComponentOutlet渲染这些组件:
<ng-container *ngFor="let c of components">
<ng-container *ngComponentOutlet="c"></ng-container>
Read these articles for more information: 阅读这些文章以获取更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.