Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Dynamically create/inject component into specific element inside *ngFor loop

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.

like image 708
somecallmemike Avatar asked May 15 '26 00:05

somecallmemike


1 Answers

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.

like image 52
Günter Zöchbauer Avatar answered May 17 '26 14:05

Günter Zöchbauer