Search code examples
angulardata-bindingangular-directive

how to bind table data cell by its data property name


Trying to do a generic dynamic table depends on collection (array) of columns with their header name and property name for the data:

columns: Array<any>= [
 {title: 'first column', name: 'subItem.propertyName1'},
 {title: 'second column', name: 'subItem.propertyName2'}
];

This is how the data structure looks like:

export class SubItem
{
   property1  :string;
   proeprty2 : string;
}

export class data 
{
   subItem : SubItem;
   AAA: string;
   BBBB:string;
}

This is the data for the table

tableData : Array<data> = jsonDataConvertedToObjectsCollection

Now, in the Html, I would like to iterate both on the column for the header lables (not a problem) and on the data items properties for cells data based on the columns name properties. I assume I can do it somehow inline (option 1) or with a directive (not teseted yet) or with a function (option 2). Looking for a working example and best practice:

<table>
 <thead>
  <th *ngFor="let columnHeader of columns">
     {{columnHeader.title}}
 </th>
</thead>
<tbody>
 <tr *ngFor="let dataItem of tableData">
   <td *ngfor = "let column of columns">
      {{dataItem[column.name]}} // option 1 - Not working
      {{getCellValue(dataItem, column.name)}} //option 2 - not working
   </td>
 </tr>
</tbody>
</table>

This is the function:

getCellValue(dataItem : data, propertyName : string)
{
    return dataItem[propertyName]
}

Solution

  • You could use lodash get. https://lodash.com/docs/4.17.15#get

    Create a pipe for the object accessing which uses the lodash function

    <tr *ngFor="let dataItem of tableData">
       <td *ngfor = "let column of columns">
          {{ dataItem | getCellValue:column.name }}
       </td>
     </tr>