首先,您需要确保您的应用程序已经安装了Angular 7。然后,按照以下步骤操作:
ng-content
标签作为表格的容器。
Name
Age
// table-container.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-table-container',
templateUrl: './table-container.component.html',
styleUrls: ['./table-container.component.css']
})
export class TableContainerComponent {
@Input() data: any[];
currentSortColumn: string;
currentSortOrder: string;
sort(column: string) {
if (this.currentSortColumn === column) {
this.currentSortOrder = this.currentSortOrder === 'asc' ? 'desc' : 'asc';
} else {
this.currentSortColumn = column;
this.currentSortOrder = 'asc';
}
this.data.sort((a, b) => {
const valueA = a[column];
const valueB = b[column];
return (valueA < valueB ? -1 : 1) * (this.currentSortOrder === 'asc' ? 1 : -1);
});
}
}
标签包装您的表格,并传递要排序的数据。
{{ item.name }}
{{ item.age }}
tableData
属性。// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
tableData = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 }
];
}
现在,当您点击表头的列时,表格的行将按照所选列进行排序。