angular - 如何将 MatSort 与 Object[] 类型的表一起使用

标签 angular

我想在对象类型的表中使用 SortHeader,我不想将表的类型更改为 MatTableDataSource,有帮助吗?

这是我的数据源

elements: Object[] = []

我应该在 ngOnInit() 中做什么? 这不起作用

this.elements.sort = this.sort;

最佳答案

您需要监听表格上的 matSortChange 事件。

<table #myTable mat-table [dataSource]="sortedData" matSort (matSortChange)="sortData($event)">

实现自定义排序逻辑并在 matSortChange 触发时提供排序后的数据。

@ViewChild('myTable') table: MatTable<Object>;

data: Object[] = [
    { name: 'Frozen yogurt', calories: 159, fat: 6, carbs: 24, protein: 4 },
    { name: 'Ice cream sandwich', calories: 237, fat: 9, carbs: 37, protein: 4 },
    { name: 'Eclair', calories: 262, fat: 16, carbs: 24, protein: 6 },
    { name: 'Cupcake', calories: 305, fat: 4, carbs: 67, protein: 4 },
    { name: 'Gingerbread', calories: 356, fat: 16, carbs: 49, protein: 4 },
];

sortedData: Object[];

constructor() {
    this.sortedData = this.data.slice();
}

sortData(sort: Sort) {
    const data = this.data.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return compare(a['name'], b['name'], isAsc);
        case 'calories': return compare(a['calories'], b['calories'], isAsc);
        case 'fat': return compare(a['fat'], b['fat'], isAsc);
        case 'carbs': return compare(a['carbs'], b['carbs'], isAsc);
        case 'protein': return compare(a['protein'], b['protein'], isAsc);
        default: return 0;
      }
    });
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

如果您在排序事件上不提供新的排序数组作为 dataSource 而是就地进行排序(在现有的 dataSource 数组中),则还必须调用 this.排序后的 table.renderRows() 因为表格不会自动检查数组是否发生更改。

https://stackblitz.com/edit/angular-dwkods

关于angular - 如何将 MatSort 与 Object[] 类型的表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55395984/

相关文章:

angular - Angular 2的 Font Awesome

html - 递归 Angular 搞乱CSS

angular - 类型错误 : Buffer is not a constructor using Angular Material Table Exporter

javascript - Typescript - 无法拼接数组

angular - 如何为 Angular 应用程序预渲染静态 HTML 页面?

angular - 对 Observable 的订阅永远不会触发

angular - 如何将自定义 css 添加到 ngx-bootstrap 工具提示?

css - 如何在 Angular v2 组件中添加样式 url?

Angular *ngIf 内存使用

javascript - 如何根据 typescript 中的键对对象数组进行排序