![](/img/trans.png)
[英]How to loop list of array in another response of array of object using *ngfor?
[英]Trying to loop through object array using ngfor using another header object array to fill a table
我正在嘗試將對象數組渲染到 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 使用標題鍵中的鍵循環遍歷數據數組中的所有對象
<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 {
}
}
有人可以幫我理解為什么嗎? 我覺得在這種情況下使用 any 不是最佳做法
定義表 header 和數據類型
export interface TableDataType {
name: string;
age: number;
job: string;
}
export interface TableHeader {
key: string;
label: string;
}
並在表格組件中使用
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
})
export class TableComponent implements OnInit {
@Input() data: Array<TableDataType>[];
@Input() headers: Array<TableHeader> = [];
constructor() {}
ngOnInit(): void {}
}
這是實時工作代碼https://stackblitz.com/edit/angular-2khgqx?file=src/app/table-demo/table.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.