You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material *ngFor循环生成的mat-table排序功能失效如何解决

问题根因

  1. Angular Material 的 matSort 指令无法直接对普通数组类型的数据源生效,必须搭配 MatTableDataSource 实例才能内置排序逻辑
  2. 你通过 *ngFor 动态生成了多个表格,仅用 @ViewChild 只能获取到第一个表格的排序实例,需要为每个表格的数据源单独绑定对应排序实例

解决方案

第一步:修改组件TS代码

首先导入必要依赖,将每个分组下的商品数组转换为MatTableDataSource实例,再通过@ViewChildren批量获取所有排序实例做绑定:

import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';

@Component({
  // 你的组件原有配置
})
export class AppComponent implements AfterViewInit {
  displayedColumns: string[] = ['name', 'price', 'quantity', 'sales'];
  // 改造groups数组,给每个分组增加MatTableDataSource类型的数据源
  groups: any[] = [
    {
      name: 'Group 1',
      items: [
        { name: 'Product 1', price: 20, quantity: 33, sales: 11 },
        { name: 'Product 2', price: 10, quantity: 43, sales: 11 },
        { name: 'Product 3', price: 23, quantity: 63, sales: 11 },
      ],
    },
    {
      name: 'Group 2',
      items: [
        { name: 'Product 2', price: 40, quantity: 33, sales: 11 },
        { name: 'Product 4', price: 10, quantity: 143, sales: 211 },
        { name: 'Product 61', price: 63, quantity: 63, sales: 151 },
      ],
    },
    {
      name: 'Group 20',
      items: [
        { name: 'Product 22', price: 40, quantity: 33, sales: 11 },
        { name: 'Product 14', price: 10, quantity: 143, sales: 211 },
      ],
    },
  ].map(group => ({
    ...group,
    dataSource: new MatTableDataSource(group.items)
  }));

  // 批量获取所有动态生成的matSort实例
  @ViewChildren(MatSort) sorts!: QueryList<MatSort>;

  ngAfterViewInit() {
    // 给每个分组的数据源绑定对应的排序实例
    this.groups.forEach((group, index) => {
      group.dataSource.sort = this.sorts.toArray()[index];
    });
  }
}

第二步:修改模板绑定

把表格的数据源从原始数组改成我们刚定义的MatTableDataSource实例即可,其他模板代码不用改动:

<!-- 仅修改这一行的dataSource绑定即可 -->
<table [dataSource]="group.dataSource" mat-table matSort>

前置检查

确保你所在的模块已经正确导入了以下依赖:

  • MatTableModule
  • MatSortModule

内容的提问来源于stack exchange,提问作者xarqt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:24:09