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;
    }

相关内容

热门资讯

透视模拟器!wpk透视辅助(透... 透视模拟器!wpk透视辅助(透视)一贯真的是有挂(详细辅助插件教程)1、起透看视 wpk透视辅助透明...
透视有挂!哈糖大菠萝有没有挂(... 透视有挂!哈糖大菠萝有没有挂(透视)确实真的有挂(详细辅助透明挂教程);1、超多福利:超高返利,海量...
透视脚本!wejoker开挂(... 透视脚本!wejoker开挂(透视)确实是真的有挂(详细辅助必胜教程)1. ai辅助创建新账号,点击...
透视存在!wepoker怎么设... 透视存在!wepoker怎么设置房间(透视)果然真的是有挂(详细辅助2025版教程)1、系统规律教程...
透视有挂!pokermaste... 透视有挂!pokermaster修改器(透视)总是是有挂(详细辅助插件教程)1、这是跨平台的黑科技,...
透视辅助!wepoker私人局... 透视辅助!wepoker私人局俱乐部怎么进(透视)果然存在有挂(详细辅助介绍教程);1、每一步都需要...
透视攻略!wepoker智能辅... 透视攻略!wepoker智能辅助插件(透视)确实真的有挂(详细辅助新2025版)透视攻略!wepok...
透视辅助!聚星ai辅助工具下载... 透视辅助!聚星ai辅助工具下载(透视)总是有挂(详细辅助2025新版教程)1、打开软件启动之后找到中...
透视软件!hhpoker是真的... 透视软件!hhpoker是真的吗(透视)好像有挂(详细辅助AA德州教程)1、ai辅助优化,发牌逻辑科...
透视好友房!hardrock透... 透视好友房!hardrock透视工具(透视)确实存在有挂(详细辅助扑克教程);1、系统规律教程、辅助...