Home > Enterprise >  Angular table row component
Angular table row component

Time:12-22

I am using angular to create a table row component that creates rows from an array of objects. However, I keep getting a file to compile error when trying to populate the data in the table.

Error: Element implicitly has an 'any' type because index expression is not of type 'number'.

enter image description here

table.component.html

<table id="users">
    <tr>
      <th *ngFor = "let column of headers">
        {{column}}
      </th>
    </tr>
  
    <tr *ngFor = "let row of rows">
      <td *ngFor = "let column of headers">
        {{row[column]}}
      </td>
    </tr>
  
  </table>

table.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent {
  headers = ["ID", "Name", "Age", "Gender", "Country"];

   rows = [{
         "ID": "1",
         "Name": "Rahul",
         "Age": "21",
         "Gender": "Male",
         "Country": "India"
      },
      {
         "ID": "2",
         "Name": "Ajay",
         "Age": "25",
         "Gender": "Male",
         "Country": "India"
      },
      {
         "ID": "3",
         "Name": "Vikram",
         "Age": "31",
         "Gender": "Male",
         "Country": "Australia"
      },
    
    
   ]

}

CodePudding user response:

Your didn't specify the types for headers and rows. It could be the root of issue as compiler doesn't know that it's an object type. Also it's not very flexible solution. Let's replace {{row[column]}} with function call {{getCellData(row, col)}} and implement the logic in ts file. Also you can review source code of existed solutions like ngx-datatable to understand how to implement really flexible and configurable grid

CodePudding user response:

You have strict mode applied to your project, which is GREAT! :) Therefore we should correctly type our data (as we always should do despite strict mode or not!)

So first of all, create a model for your Array, I prefer interfaces:

export interface RowData {
  ID: string;
  Name: string;
  Age: string;
  Gender: string;
  Country: string;
}

Cool, now we can use that to tell Angular in your component, or rather TypeScript, that our array looks like RowData:

rows = [...] as RowData[];

Now to the headers... we need to tell that the array we are providing presents keys of our model RowData so we can use that in the template without getting that error:

headers = ['ID', 'Name', 'Age', 'Gender', 'Country'] as Array<keyof RowData>;

Now we are good to go!

  • Related