我正在尝试将对象数组呈现到collectionsHome组件中的表组件中
收集主页组件:
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 {
}
}
表组件
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
我使用ngfor循环遍历数据数组中的所有对象,使用的键来自header键
<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>
执行此操作{{record[header.key]}}会引发错误,我不确定原因
错误如下:
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.
唯一的方法是将输入类型更改为如下所示的任何类型
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 {
}
}
有人能帮我理解为什么吗?我觉得在这种情况下使用任何方法都不是最佳做法
1条答案
按热度按时间tyky79it1#
定义表头和数据类型,如
并用于表组件
这是带电工作的代码https://stackblitz.com/edit/angular-2khgqx?file=src/app/table-demo/table.component.ts