在Angular 7中,可以使用自定义数据源排序的方法来对数据进行排序。下面是一个示例,包含了排序的代码:
CustomDataSource
的自定义数据源类,继承自DataSource
类,并实现connect
和disconnect
方法。import { DataSource } from '@angular/cdk/table';
import { Observable, BehaviorSubject } from 'rxjs';
export class CustomDataSource extends DataSource {
private dataSubject = new BehaviorSubject([]);
connect(): Observable {
return this.dataSubject.asObservable();
}
disconnect() {
this.dataSubject.complete();
}
setData(data: any[]) {
this.dataSubject.next(data);
}
sortBy(property: string) {
// 获取当前数据
const data = this.dataSubject.getValue();
// 根据指定的属性对数据进行排序
data.sort((a, b) => {
if (a[property] < b[property]) {
return -1;
} else if (a[property] > b[property]) {
return 1;
} else {
return 0;
}
});
// 更新排序后的数据
this.dataSubject.next(data);
}
}
CustomDataSource
来展示数据,并添加排序按钮。import { Component } from '@angular/core';
import { CustomDataSource } from './custom-data-source';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
dataSource: CustomDataSource;
constructor() {
this.dataSource = new CustomDataSource();
}
// 设置初始数据
ngOnInit() {
const initialData = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 }
];
this.dataSource.setData(initialData);
}
sortBy(property: string) {
this.dataSource.sortBy(property);
}
}
这样,当点击“Sort by Name”按钮时,数据会根据name
属性进行排序;当点击“Sort by Age”按钮时,数据会根据age
属性进行排序。