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

相关内容

热门资讯

科普透视!epoker免费透视... 科普透视!epoker免费透视脚本!其实一直总是有辅助脚本(有挂教程)-哔哩哔哩epoker免费透视...
科普透视!红龙poker作必弊... 科普透视!红龙poker作必弊指令!真是真的是有辅助神器(今日头条)-哔哩哔哩1、用户打开应用后不用...
解密透视!竞技联盟辅助!一直是... 解密透视!竞技联盟辅助!一直是真的有辅助软件(有挂猫腻)-哔哩哔哩1、起透看视 竞技联盟辅助辅助软件...
分享透视!pokerworld... 分享透视!pokerworld修改器!确实存在有辅助方法(有挂分享)-哔哩哔哩亲,关键说明,poke...
了解透视!newpoker怎么... 了解透视!newpoker怎么安装脚本!都是真的是有辅助app(有挂技巧)-哔哩哔哩1、点击下载安装...
揭幕透视!哈糖大菠萝有挂吗!一... 揭幕透视!哈糖大菠萝有挂吗!一贯一直都是有辅助方法(有挂技巧)-哔哩哔哩1、超多福利:超高返利,海量...
解密透视!sohoo poke... 解密透视!sohoo poker辅助器!其实存在有辅助脚本(有挂教学)-哔哩哔哩1、完成sohoo ...
必备透视!佛手在线大菠萝智能辅... 您好,佛手在线大菠萝智能辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
揭露透视!约局吧透视挂下载!真... 揭露透视!约局吧透视挂下载!真是一直都是有辅助技巧(有挂头条)-哔哩哔哩1、下载好约局吧透视挂下载透...
了解透视!哈糖大菠萝攻略!一贯... 了解透视!哈糖大菠萝攻略!一贯真的有辅助方法(详细教程)-哔哩哔哩1、哈糖大菠萝攻略模拟器是什么优化...