0

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.

2
  • What result are you getting? That would help us better understand your issue. Commented Dec 19, 2019 at 15:23
  • I would also recommend using @ViewChild('preGrid', { read: ViewContainerRef }) entry: ViewContainerRef; instead of document.getElementById Commented Dec 19, 2019 at 15:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, I probably tried to fix the problem by hard way.it's easier acording to my solution...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.