I am trying to render an array of objects into a table component inside the collectionsHome Component
CollectionsHomeComponent:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-collections-home',
templateUrl: './collections-home.component.html',
styleUrls: ['./collections-home.component.css']
})
export class CollectionsHomeComponent implements OnInit {
data = [
{name: 'James', age: 24, job: 'Designer'},
{name: 'Jill', age: 26, job: 'Engineer'},
{name: 'Elyse', age: 25, job: 'Engineer'}
];
headers=[
{key:'name', label: 'Name'},
{key:'age', label: 'Age'},
{key:'job', label: 'Job'}
]
constructor() { }
ngOnInit(): void {
}
}
TableComponent
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
@Input() data: {name: string; age: number; job: string}[] = [];
@Input() headers: {key: string; label: string}[] = [];
constructor() { }
ngOnInit(): void {
}
}
CollectionsHomeComponent.html
<app-divider>Table Component</app-divider>
<app-table [data]="data" [headers]="headers"></app-table>
TableComponent.html
I am using ngfor to loop through all the objects in the data array using the key from the headers keys
<table class="ui table">
<thead>
<tr>
<th *ngFor="let header of headers">
{{header.label}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let record of data">
<td *ngFor="let header of headers">
{{record[header.key]}} ---> Throwing Error
</td>
</tr>
</tbody>
</table>
doing this {{record[header.key]}} throws an error and I am not sure why
Here is the error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; age: number; job: string; }'.
No index signature with a parameter of type 'string' was found on type '{ name: string; age: number; job: string; }'.ngtsc(7053)
table.component.ts(4, 40): Error occurs in the template of component TableComponent.
The only way to get this working is if I change the input types to any like this
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
@Input() data: any = [];
@Input() headers: any = [];
constructor() { }
ngOnInit(): void {
}
}
Can someone help me understand why? I feel like using any in cases like this is not best practices
define the table header and data type like
and use in table component
here is the live working code https://stackblitz.com/edit/angular-2khgqx?file=src/app/table-demo/table.component.ts