我必须使用哪种逻辑来对元素进行排序?
在这里,我生成所有的列和行。
dynamic-table.component.html
<table>
<tr>
<th *ngFor="let col of columns" (click)="onClickSort()">{{col}}</th>
</tr>
<tr *ngFor="let user of users">
<td *ngFor="let col of columns">{{user[col]}}</td>
</tr>
</table>dynamic-table.component.ts
import {Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-dynamic-table',
templateUrl: './dynamic-table.component.html',
styleUrls: ['./dynamic-table.component.css']
})
export class DynamicTableComponent implements OnInit {
@Input()
users = [];
@Input()
columns: string[];
constructor() {
}
onClickSort() {
//ADD LOGIC SORT
}
ngOnInit() {
}
}我的数据在mock.ts中,我可以在我的服务中找到它们。
app.component.ts
import {Component, OnInit } from '@angular/core';
import {TableService} from './table.service';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
users;
columns;
constructor(private atService: TableService) {
}
ngOnInit(): void {
this.columns = this.atService.getColumns();
this.atService.getUsers().subscribe((res) => this.users = res);
}
}发布于 2019-03-01 02:14:01
您可以编写一个pipe,它接受数据并返回以您喜欢的方式排序的数据。
<li *ngFor="let item of items | sortingPipe: filterarg">myfilter管道将执行以下操作:
@Pipe({
name: 'sortingPipe'
})
export class SortingPipe implements PipeTransform {
transform(myArr, filterArg) {
const sorted = myArr.sort((x, y) => {
return x.duration - y.duration; // whatever you want to compare
});
return sorted.slice(0);
}
}发布于 2019-03-01 01:55:48
有一个很好的库可以做到这一点
https://www.kryogenix.org/code/browser/sorttable/
它非常容易使用。
只需在html文件中加载脚本并修改头文件,将sortable (带有一个t)添加为一个类,如下所示:
<script src="sorttable.js"></script>
<table>
<tr>
<th *ngFor="let col of columns">{{col}}</th>
</tr>
<tr *ngFor="let user of users">
<td *ngFor="let col of columns">{{user[col]}}</td>
</tr>
</table>发布于 2019-03-01 02:05:12
我是ngx-datatable的粉丝-这是一个用于美观表格的库,具有排序和搜索功能。
sorting的一个例子就是向<ngx-datatable></<ngx-datatable>组件添加一个属性。
https://stackoverflow.com/questions/54931303
复制相似问题