Angularmaterial排序表头在更改数据源后无法工作
创始人
2024-10-28 10:01:04
0

在更改数据源后,需要手动重新设置排序表头的数据源。这可以通过以下步骤实现:

  1. 在 HTML 模板中,找到包含排序表头的 mat-table 元素,将其绑定到模板引用变量中:

  2. 在组件类中,使用 ViewChild 装饰器和 @Input() 装饰器声明这个引用变量:

    @ViewChild('table') table: MatTable; @Input() dataSource: MatTableDataSource;

  3. 在更改数据源后,重新设置表头的数据源:

    this.dataSource = new MatTableDataSource(data); this.table.dataSource = this.dataSource;

  4. 现在,表头排序应该正常工作了。

完整的代码示例:

HTML 模板:


  
     Name 
     {{item.name}} 
  
  
     Age 
     {{item.age}} 
  
  
  

组件类:

import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
  displayedColumns: string[] = ['name', 'age'];
  dataSource: MatTableDataSource;

  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild('table') table: MatTable;
  @Input() data: any[];

  ngOnInit() {
    this.dataSource = new MatTableDataSource(this.data);
    this.dataSource.sort = this.sort;
    this.table.dataSource = this.dataSource;
  }

  ngOnChanges(changes) {
    if (changes.data) {
      this.dataSource = new MatTableDataSource(changes.data.currentValue);
      this.dataSource.sort = this.sort;
      this.table.dataSource = this.dataSource;
    }

相关内容

热门资讯

透视好友“sohoo竞技联盟辅... 透视好友“sohoo竞技联盟辅助器”透视辅助工具(切实有挂);sohoo竞技联盟辅助器辅助器中分为三...
透视能赢!德普之星透视辅助,德... 透视能赢!德普之星透视辅助,德扑之心免费透视,2025新版总结(有挂辅助)1、超多福利:超高返利,海...
透视黑科技“竞技联盟透视”透视... 透视黑科技“竞技联盟透视”透视辅助插件(真是真的有挂)1、用户打开应用后不用登录就可以直接使用,点击...
透视黑科技!德普之星私人局辅助... 透视黑科技!德普之星私人局辅助免费,(德扑之心)确实存在有挂,微扑克教程(有挂技巧)1、完成德普之星...
透视安装“sohoo poke... 透视安装“sohoo poker辅助器”透视辅助助手(本来是有挂);1、sohoo poker辅助器...
透视攻略!德普之星私人局辅助免... 透视攻略!德普之星私人局辅助免费,德普之星透视辅助插件,技巧教程(有挂插件)1、德普之星私人局辅助免...
透视免费“约局吧是否有挂”透视... 透视免费“约局吧是否有挂”透视辅助器(切实是有挂)约局吧是否有挂辅助器中分为三种模型:约局吧是否有挂...
透视辅助!德扑圈透视挂,(德普... 透视辅助!德扑圈透视挂,(德普)真是真的有挂,科技教程(有挂插件)1、每一步都需要思考,不同水平的挑...
辅助透视!xpoker怎么作弊... 辅助透视!xpoker怎么作弊,epoker有透视吗,揭秘攻略(有挂细节);1、epoker有透视吗...
透视挂!德扑圈透视挂,(德普之... 透视挂!德扑圈透视挂,(德普之星)确实有挂,实用技巧(有挂攻略)1、上手简单,内置详细流程视频教学,...