简体   繁体   English

Angular 在所需组件内创建动态组件

[英]Angular Creating Dynamic Component Inside Desired Component

I am trying to create a component inside html table 's each td child dynamicly.我正在尝试在html table的每个 td 子项中动态创建一个组件。 I created a table component like following code (inside app.component.html )我创建了一个类似于以下代码的table组件(在app.component.html

<div class="container">
  <table class="table">
    <thead>
        <tr>
            <th scope="col" *ngFor="let column of columns">{{column}}</th>
         </tr>
    </thead>
    <tbody #preGrid id="focusItem">

    </tbody>
  </table>
</div>

app.component.ts file seems as follow. app.component.ts文件如下所示。

ngOnInit() {
    let tableItem = document.getElementById("focusItem");
    let lastTR;
    for (let i = 0; i < 12; i++) {
      if (i % this.columns.length == 0) {
        let tr = document.createElement("tr");
        tableItem.appendChild(tr);
      }
      lastTR = this.getLastNode(tableItem);
      let td = document.createElement("td");
      lastTR.appendChild(td);

      const factory = this.resolver.resolveComponentFactory(
        CustomInputComponent
      );
      this.container.createComponent(factory);
    }
  }

I am trying to create angular components by dynamicly using ComponentFactoryResolver .To draw this component, I used ViewContainerRef .But seems, it is not true way to do this.Coz I cannot create my CustomInputComponent inside td component via this way.我正在尝试通过动态使用ComponentFactoryResolver来创建角度ComponentFactoryResolver 。为了绘制这个组件,我使用了ViewContainerRef 。但似乎,这不是真正的方法。因为我无法通过这种方式在 td 组件中创建我的CustomInputComponent What I am trying to do is, embeding CustomInputComponent inside each td elements.You can see what I wrote till now here .我想要做的是,将 CustomInputComponent 嵌入到每个 td 元素中。您可以在这里看到我到现在为止写的内容。

You need to create an array of object which will have the props as well as the type of component you want to render, then in the html portion you can have an ngFor loop to iterate over that array of object.您需要创建一个对象数组,其中包含要呈现的道具以及组件的类型,然后在 html 部分中,您可以使用ngFor循环来遍历该对象数组。 Inside the ngFor loop have multiple ngSwitchCase to render the correct control for the current iteration.ngFor循环内部有多个ngSwitchCase来呈现当前迭代的正确控制。

Please see this link : https://codeburst.io/angular-dynamic-forms-ng-switch-approach-4f267c01d2c6请参阅此链接: https : //codeburst.io/angular-dynamic-forms-ng-switch-approach-4f267c01d2c6

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

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