'ng-zorro antd, nz-table dynamic table columns and rows

I have a table where columns and row cells are dynamically set, in the table header th content should be dynamic and also for table body tr maybe contain HTML that contains another component tag.

is there any way to handle that, I have created a component called table and this table has @Input and @Output to be reusable for different usage.

in the ng-zorro documentation, there is no way to use the table data source technique so I can use render functions like react and.

enter image description here

enter image description here



Solution 1:[1]

You can create two inputs, one for the columns and one for the rows.

To make the columns dynamically you have to send to the column input an array with column objects. There you can set everything that you want. I usually use the tittle and the column function like that:

listOfColumn = [
    {
      title: 'Code',
      compare: (a: User, b: User) => a.code.localeCompare(b.code)
    },
    {
      title: 'Customer',
      compare: (a: User, b: User) => a.name.localeCompare(b.name)
    }
]

The html code to use it is the following:

<thead>
    <tr>
      <th *ngFor="let column of listOfColumn" [nzSortFn]="column.compare">{{ column.title }}</th>
    </tr>
</thead>

And for the data, just send it to other input and set the array as data input for the table and make a loop to display the content:

<nz-table
  #basicTable
  [nzData]="data">
  <thead>
    <tr>
      <th *ngFor="let column of listOfColumn" [nzSortFn]="column.compare">{{ column.title }}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of basicTable.data">
      <td>{{ user.code }}</td>
      <td>{{ user.name }}</td>
  </tbody>
</nz-table>

I hope I answer your question :D

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 borjaj