Render dynamic HTML using UI Library

254 views Asked by At

I'm using UI Library Ant Design in Angular Project. I'm trying to render dynamic HTML inside but using UI library component, like this

My component.ts:

test : any;

ngAfterViewInit() {
    setTimeout(() => {
        this.test = this.domSanitizer.bypassSecurityTrustHtml('<nz-table>
             <thead>
              <td>Header 1</td>
              <td>Header 2</td>
             </thead>
             <tbody>
              <tr>
               <td>Value 1</td>
               <td>Value 2</td>
              </tr>
             </tbody>
            </nz-table>')
    }, 0);
}

My component.html:

<div [innerHtml]="test"></div>

But this is what I received

Header 1Header 2Value 1Value 2

So, how I can render dynamic HTML inside AntDesign's Nz-Table Component?

1

There are 1 answers

3
Zerotwelve On

You should not use innerHTML but an *ngFor. Your code example is very poor but I will do my best:

const tableData = {
   headers: ["Header 1","Header 2"],
   rows: [
      ["row 1 value1","row 1 value2"],
      ["row 2 value1","row 2 value2"],
      ["row 3 value1","row 3 value2"]
   ]
}

in your HTML templare

<nz-table>
<thead>
  <td *ngFor="let header of tableData.headers">{{header}}</td>
</thead>
<tbody>
   <tr *ngFor="values of tableData.rows">
      <td *ngFor="let value of values">{{value}}</td>
   </tr>
</tbody>
</nz-table>

As you can see tableData can be anything, you can push row into it and the table will update. You can also get the value from an API or whatever you want. You can also use JSON object instead of all this arrays and use keyvalue pairs if you want.