我有一个Angular 13应用程序&构建一个名为app-table的通用可重用组件
html
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>DOB</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of tableItems">
<td> {{ item.name }}</td>
<td> {{ item.email } </td>
<td> {{ item.dob }} </td>
</tr>
</tbody>
</table>component.ts
import { Component, Input, OnInit} from '@angular/core';
import { TableItem } from './model/tableItem';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css'],
})
export class TableComponent implements OnInit {
@Input() tableItems: TableItem[] = [];
constructor() {}
ngOnInit(): void {}
}目前,这在4-5个地方是可重用的,但是该组件的可重用性与name、email、dob字段相关联。我想让它成为通用的,这样任何模型都可以链接到这个组件&可以在整个应用程序中重用。
请建议一下。谢谢!
发布于 2022-08-04 20:31:42
您可以从对象键获取列名,并使用*ngFor对它们进行迭代,例如:
在TableComponent模板文件中
<table>
<thead>
<tr>
<th *ngFor="let header of data[0] | keyvalue: sortNull">{{ header.key }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of data">
<td *ngFor="let cell of row | keyvalue: sortNull">{{ cell.value }}</td>
</tr>
</tbody>
</table>在打字记录文件中
export class TableComponent {
@Input() data: any[] = [];
sortNull() { return 0; }
}sortNull()只是一个比较器函数,它总是return 0来维护键/值对的插入顺序。
并供使用
@Component({
selector: 'app-user-list',
template: `<app-table [data]="data"></app-table>`
})
export class UserListComponent {
data = [
{ name: 'John', email: 'john@example.com', dob: '2001/01/01' },
{ name: 'Jane', email: 'jane@example.com', dob: '2002/02/02' },
{ name: 'Kane', email: 'kane@example.com', dob: '2003/03/03' },
]
}发布于 2022-08-04 18:22:00
有很多方法可以这样做,最简单的方法是添加另一个接受列列表的输入,然后根据该列表填充您的表头。就像这样。
<table class="table table-striped">
<thead>
<tr>
<ng-container *ngFor="let column of columns">
<th>{{column}}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of tableItems">
<ng-container *ngFor="let column of columns">
<td>{{item[column]}}</td>
</ng-container>
</tr>
</tbody>
</table> 你的组件就会像这样。
columns = ['name','email','dob']
tableItems = [
{
name: 'test',
dob: '31/12/1990',
email: 'email@test.com'
}
];但是表组件确实很难维护和扩展,它们需要很大的努力,这不是你随便做的事情。我建议找到一个构建了一个非常好的表组件的库,并使用它,这取决于您的需求,很少有例子是ngx轻松表、角cdk表等等。
https://stackoverflow.com/questions/73239698
复制相似问题