seyid yagmur
seyid yagmur

Reputation: 1712

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.

Upvotes: 0

Views: 133

Answers (1)

Shekher Khare
Shekher Khare

Reputation: 61

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

Upvotes: 1

Related Questions