Search code examples
htmlangularobjectcomponentsngfor

Dynamic table component that automatically list each property value of the current Object data iteration (ngFor directive);


Going to the point, I'm creating a table component that receives an Object containing all information that the dynamic table needs, including head information and so on. My mission is to make it possible for every row (data), my table doesn't need to know the property name, only list its value straight away.

I did some console tests and it seems to work around those lines:

const dataList = [
  { name: 'Eugene', age: 20, alive: true },
  { name: 'Game Master', age: 40, alive: false },
  { name: 'Camel', age: 22, alive: true }
];


for(let data of dataList) {
  console.log("All data info");
  console.log(data);

  for(let propertyValue of Object.values(data)) {
    console.log(propertyValue);
  }
}

The Results:

VM1123:2 All data info
VM1123:3 {name: 'Eugene', age: 20, alive: true}
VM1123:6 Eugene
VM1123:6 20
VM1123:6 true
VM1123:2 All data info
VM1123:3 {name: 'Game Master', age: 40, alive: false}
VM1123:6 Game Master
VM1123:6 40
VM1123:6 false
VM1123:2 All data info
VM1123:3 {name: 'Camel', age: 22, alive: true}
VM1123:6 Camel
VM1123:6 22
VM1123:6 true


I'm trying to achieve the same result, but this time iterating between ngFor directive, like below:
<tr *ngFor="let data of tableConfig.data; let i = index">
  <td *ngFor="let propValue of Object.values(data)"> {{ propValue }}</td>



But, the problem is that I can't access the 'Object' class inside the component HTML.

Property 'Object' does not exist on type 'PaginationTableComponent'.


Solution

  • Add method to get your object values like

    getValues(data): any{
      return Object.values(data);
    }
    

    In template :

    <td *ngFor="let propValue of getValues(data)"> {{ propValue }}</td>
    

    Demo