Angular中的Material表格排序不起作用
创始人
2024-10-31 07:30:33
0
  1. 确保您已添加对@angular/material和@angular/cdk的依赖。
  2. 在组件中引入MatSort和MatSortable,并将MatSort指令添加到表格中。
import { MatSort, MatSortable } from '@angular/material';

@Component({
  selector: 'app-my-table',
  templateUrl: './my-table.component.html',
  styleUrls: ['./my-table.component.css']
})
export class MyTableComponent implements OnInit {
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  dataSource = new MatTableDataSource([]);
  displayedColumns: string[] = ['name', 'age', 'gender'];

  ngOnInit() {
    this.dataSource.sort = this.sort;
  }

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

    this.dataSource.data = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return this.compare(a.name, b.name, isAsc);
        case 'age': return this.compare(a.age, b.age, isAsc);
        case 'gender': return this.compare(a.gender, b.gender, isAsc);
        default: return 0;
      }
    });
  }

  compare(a: number | string, b: number | string, isAsc: boolean) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
  }
}
  1. 在HTML中添加MatSortHeader指令,并绑定sort对象。

        
        
        

相关内容

热门资讯

有玩家发现"hhpo... 有玩家发现"hhpoker辅助软件是真的么"wepoker辅助分析器(一贯存在有辅助神器)-哔哩哔哩...
今天下午"wepok... 今天下午"wepoker破解器"wepoker开辅助能查到吗(切实真的是有辅助工具)-哔哩哔哩一、w...
近日"hhpoker... 近日"hhpoker辅助器"德普之星怎么设置埋牌(总是真的有辅助神器)-哔哩哔哩1、完成德普之星怎么...
最终"wepoker... 最终"wepoker怎么开辅助"pokemmo内置修改器(竟然是有辅助软件)-哔哩哔哩1、进入游戏-...
透视辅助"wepok... 透视辅助"wepoker软件安装包"wepoker免费脚本咨询(本来存在有辅助辅助器)-哔哩哔哩一、...
据公告内容"wepo... 据公告内容"wepoker的辅助器"epoker透视(原来是有辅助神器)-哔哩哔哩1、进入游戏-大厅...
透视有挂"wepok... 透视有挂"wepoker免费钻石"wpk辅助器是真的吗(都是真的是有辅助软件)-哔哩哔哩1、下载好w...
这一问题亟待解决"约... 这一问题亟待解决"约局吧德州有挂吗"佛手在线大菠萝辅助(竟然有辅助插件)-哔哩哔哩1、下载好佛手在线...
据了解"wepoke... 据了解"wepoker有人用过吗"红龙poker辅助(果然存在有辅助神器)-哔哩哔哩1、操作简单,无...
近日"wepoker... 近日"wepoker透视脚本是什么"werplan脚本(都是真的是有辅助工具)-哔哩哔哩;1、该软件...
Name {{ element.name }} Age {{ element.age }} Gender {{ element.gender }}