I am looping through a list of metrics and inside each loop there is a button that would be clicked to render a graph at a specific div within the HTML of the loop. The graph is a separate component, however I cannot seem to figure out how to target the correct HTML element to load the graph component into. I started by creating a component rendering function and call it like this:
loadMetricGraph(metric) {
let selector = "[id=metricGraph-" + metric.id + "]";
this.renderComponent(LineGraphHorizontalComponent, selector, metric.data);
}
renderComponent(componentClass, selector, data) {
return this.compiler
.compileComponentAsync(componentClass)
.then((factory:ComponentFactory<any>) => {
let cmpRef:ComponentRef<any> =
factory.create(this.injector, null, selector);
cmpRef.instance.inputData = data;
(<any>this.appRef)._loadComponent(cmpRef);
return cmpRef;
});
}
In the loop I have a div that would be the target for the loaded component, however I am stuck on how to pass the correct selector to the renderComponent() function. I have attempted to use
id="graphData-{{ metric.id }}" And then a selector of "[id=graphData-" + metric.id + "]". I know this is not the correct way to do this, but I am not sure how to proceed.
You can't dynamically add HTML and get components or directives created for this HTML. If you want to dynamically add components then you need to use ViewContainerRef.createComonent.
See Angular 2 dynamic tabs with user-click chosen components shows how to do this declaratively using a helper component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With