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

相关内容

热门资讯

wepoker辅助软件价格!德... wepoker辅助软件价格!德普之星透视辅助插件(透视)攻略-真是必备存在有挂暗藏猫腻,小编详细说明...
透视科普!wepoker透视方... 透视科普!wepoker透视方法(透视)hhpoker辅助,教程手筋(新版有挂)-哔哩哔哩一、wep...
wepokerplus开挂!p... wepokerplus开挂!pokemmo手机脚本(透视)脚本-其实教你是真的挂1、点击下载安装,p...
透视分享!wepoker手机版... 透视分享!wepoker手机版辅助(透视)wepoker看底牌,教程绝活(了解有挂)-哔哩哔哩1、点...
破解辅助插件wepoker!来... 破解辅助插件wepoker!来玩app破解(透视)神器-一贯科普是有挂1、破解辅助插件wepoker...
透视揭幕!wepoker底牌透... 透视揭幕!wepoker底牌透视(透视)wepoker辅助脚本,教程资料(有挂攻略)-哔哩哔哩该软件...
fishpoker透视!hhp... fishpoker透视!hhpoker一直输有挂吗(透视)教程-都是开挂真的是有挂1、hhpoker...
透视总结!wepoker底牌透... 透视总结!wepoker底牌透视脚本(透视)wepoker透视脚本安卓,教程绝活(证实有挂)-哔哩哔...
拱趴大菠萝有什么挂!约局吧游戏... 拱趴大菠萝有什么挂!约局吧游戏挂(透视)工具-一贯揭露是真的挂1、拱趴大菠萝有什么挂脚本辅助下载、拱...
透视关于!hh poker插件... 透视关于!hh poker插件下载(透视)约局吧开挂神器是真的吗,教程手段(有挂规律)-哔哩哔哩1、...