You need to enable JavaScript to run this app. Angular matTabGroup多标签页下实现matSort跨标签统一排序
优惠活动
大模型
产品
解决方案
定价
更多

Angular matTabGroup多标签页下实现matSort跨标签统一排序

解决方案

问题根因

  • @ViewChild(MatSort) 默认仅能匹配到页面中第一个渲染的MatSort实例,你两个标签页各有一个独立的MatSort,默认只能拿到第一个激活标签的排序实例
  • MatTab组件默认开启懒加载,未激活标签的DOM不会初始化,第二个标签的MatSort实例在页面加载时不存在
  • 两个MatSort实例各自独立,排序状态没有做全局同步,导致排序逻辑无法跨标签复用

代码修改

1. TS文件修改

// 先导入所需依赖
import { QueryList, ViewChildren } from '@angular/core';
import { MatTabChangeEvent } from '@angular/material/tabs';
import { MatSort, Sort } from '@angular/material/sort';

export class NcsatsHomeComponent implements OnInit, AfterViewInit {
  dataSource = new MatTableDataSource<any>([]);
  dataSource2 = new MatTableDataSource<any>([]);

  // 替换原有@ViewChild,获取所有MatSort实例
  @ViewChildren(MatSort) sortList: QueryList<MatSort>;    
  @ViewChild(MatPaginator) paginator: MatPaginator;

  // 全局存储排序状态
  currentSort: Sort = {active: '', direction: ''};

  displayedColumns: string[] = ['CauseEffect', 'nonconSys', 'nonconRec', 'partNumber', 'partName']
  displayedColumns1: string[] = ['CauseEffect1', 'nonconSys1', 'nonconRec1', 'partNumber1', 'partName1']
  displayedColumns2: string[] = ['CauseEffect', 'nonconSys', 'nonconRec', 'discrepancyShort', 'dispositionShort']
  displayedColumns3: string[] = ['CauseEffect1', 'nonconSys1', 'nonconRec1', 'discrepancyShort1', 'dispositionShort1']

  ngOnInit(): void {
    this.getData();
  }

  ngAfterViewInit(): void {
    // 监听MatSort实例变化,绑定排序事件
    this.sortList.changes.subscribe(() => {
      this.bindSortEvents();
      // 初始化时绑定第一个标签的Sort
      if (this.sortList.first) {
        this.syncSortToInstance(this.sortList.first);
        this.dataSource.sort = this.sortList.first;
      }
    });
  }

  // 绑定所有MatSort的排序变更事件,同步全局状态
  bindSortEvents() {
    this.sortList.forEach(sort => {
      sort.sortChange.subscribe((sortState: Sort) => {
        this.currentSort = sortState;
        // 同步排序状态到所有MatSort实例
        this.sortList.forEach(s => {
          if (s !== sort) {
            this.syncSortToInstance(s);
          }
        });
      });
    });
  }

  // 将全局排序状态同步到指定MatSort实例
  syncSortToInstance(sort: MatSort) {
    if (!sort) return;
    sort.active = this.currentSort.active;
    sort.direction = this.currentSort.direction;
    sort.sortChange.emit(this.currentSort);
  }

  // 标签切换事件处理
  onTabChange(event: MatTabChangeEvent) {
    // 切换后获取当前标签的MatSort实例,绑定给数据源
    const currentSort = this.sortList.get(event.index);
    if (currentSort) {
      this.syncSortToInstance(currentSort);
      this.dataSource.sort = currentSort;
    }
  }

  getData(){
    this.loggedIn = this.authenticationService.loginNeeded();
    console.log('login check', this.loggedIn);
    if(this.loggedIn){
      this.isLoading = true
      this.isempty = false;
      setTimeout(() => {
        this.repoService.getEntries(0,1000).subscribe(largeDataSet => {
          this.dataSource.paginator = this.paginator;
          // 移除原有的固定sort绑定,改为动态绑定
          this.dataSource.data = largeDataSet;
          this.dataSource.data.forEach(element => {Object.keys(element).forEach(k => element[k] = element[k] === null ? '' : element[k])});
          console.log(this.dataSource.data);
          this.dataSource2.data = this.dataSource.data;
          this.isLoading = false;
          this.runAllChanges();
        })
      })
    } else {
      this.router.navigateByUrl('/');
    }

  }
}

2. HTML文件修改

给mat-tab-group添加标签切换事件监听:

<mat-tab-group mat-align-tabs="center" [selectedIndex]="mytab" (selectedTabChange)="onTabChange($event)">
  <!-- 原有标签内容保持不变 -->
</mat-tab-group>

逻辑说明

任意标签页触发展排序操作时,排序状态会先同步到全局变量存储,同时会同步给所有已渲染的MatSort实例。切换标签页时,会自动把全局排序状态同步给当前激活标签的MatSort,再绑定到数据源,实现跨标签页的排序能力复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:15:06