在Angular 5中,我们可以为表格列进行排序并显示相应的图标(用于取消排序)。下面是一个示例解决方案:
import { Component } from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent {
tableData = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 },
{ name: 'Alice', age: 35 }
];
sortColumn: string = '';
sortDirection: string = '';
}
Name
Age
{{ item.name }}
{{ item.age }}
sort
方法来处理排序逻辑:sort(column: string) {
if (this.sortColumn === column) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortColumn = column;
this.sortDirection = 'asc';
}
}
sort
的自定义管道来实现排序:import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(array: any[], column: string, direction: string): any[] {
if (!array || !column || !direction) {
return array;
}
return array.sort((a, b) => {
let aValue = a[column];
let bValue = b[column];
if (typeof aValue === 'string') {
aValue = aValue.toLowerCase();
}
if (typeof bValue === 'string') {
bValue = bValue.toLowerCase();
}
if (aValue < bValue) {
return direction === 'asc' ? -1 : 1;
}
if (aValue > bValue) {
return direction === 'asc' ? 1 : -1;
}
return 0;
});
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { TableComponent } from './table/table.component';
import { SortPipe } from './sort.pipe';
@NgModule({
declarations: [
AppComponent,
TableComponent,
SortPipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当点击表格列标题时,表格将按照相应的列进行排序,并显示对应的排序图标。再次点击标题,可以反转排序顺序。