I have a requirement to display an array of objects in a table component within 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 iterate through the objects in the data array based on the keys provided in the headers
<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>
The code {{record[header.key]}} is causing an error and I'm unsure why
Here is the error message:
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 workaround I found is by changing 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