简体   繁体   English

Angular 2 - 动态创建/注入组件到* ngFor循环内的特定元素

[英]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. 我循环遍历一个度量列表,并在每个循环内部有一个按钮,可以单击该按钮在循环的HTML内的特定div处呈现图形。 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. 该图是一个单独的组件,但我似乎无法弄清楚如何定位正确的HTML元素以加载图形组件。 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. 在循环中,我有一个div,它将成为加载组件的目标,但是我仍然坚持如何将正确的选择器传递给renderComponent()函数。 I have attempted to use id="graphData-{{ metric.id }}" And then a selector of "[id=graphData-" + metric.id + "]" . 我试图使用id="graphData-{{ metric.id }}"然后选择"[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. 您无法动态添加HTML并获取为此HTML创建的组件或指令。 If you want to dynamically add components then you need to use ViewContainerRef.createComonent . 如果要动态添加组件,则需要使用ViewContainerRef.createComonent

See Angular 2 dynamic tabs with user-click chosen components shows how to do this declaratively using a helper component. 通过用户单击选择的组件查看Angular 2动态选项卡,显示如何使用帮助程序组件以声明方式执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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