简体   繁体   中英

Angular Creating Dynamic Component Inside Desired Component

I am trying to create a component inside html table 's each td child dynamicly. I created a table component like following code (inside 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.

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. What I am trying to do is, embeding CustomInputComponent inside each td elements.You can see what I wrote till now here .

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. Inside the ngFor loop have multiple ngSwitchCase to render the correct control for the current iteration.

Please see this link : https://codeburst.io/angular-dynamic-forms-ng-switch-approach-4f267c01d2c6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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