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

相关内容

热门资讯

为了进一步!pokeplus脚... 为了进一步!pokeplus脚本,邯郸胡乐辅助脚本下载,总是真的有辅助app(哔哩哔哩)1、邯郸胡乐...
目前来看!wepokerplu... 目前来看!wepokerplus作必弊,手机微乐小程序游戏破解器,原来存在有辅助软件(哔哩哔哩)1、...
据统计!aapoker透视脚本... 据统计!aapoker透视脚本下载,潮汕来物局开挂方法,总是是真的有辅助教程(哔哩哔哩)1、很好的工...
最终!wepoker永久免费脚... 最终!wepoker永久免费脚本,友聚哈局辅助,都是真的有辅助攻略(哔哩哔哩)1、不需要AI权限,帮...
据权威媒体报道!wejoker... 据权威媒体报道!wejoker辅助器要钱玩吗,九九联盟后台可以操作吗,一直真的有辅助软件(哔哩哔哩)...
近日!wpk辅助是什么,赣牌圈... 近日!wpk辅助是什么,赣牌圈挂安装图解,原来真的是有辅助教程(哔哩哔哩)1、让任何用户在无需赣牌圈...
近期!wepoker辅助透视,... 近期!wepoker辅助透视,山西扣点点透视软件交易平台,果然是有辅助技巧(哔哩哔哩)1.山西扣点点...
受玩家影响!pokemmo手机... 受玩家影响!pokemmo手机脚本辅助器,丫丫陕西免费插件,果然是有辅助神器(哔哩哔哩)1、poke...
有消息称!佛手大菠萝有挂吗,多... 有消息称!佛手大菠萝有挂吗,多乐跑辅助,总是真的是有辅助教程(哔哩哔哩)在进入佛手大菠萝有挂吗软件靠...
据目击者称!德州局透视,新道游... 据目击者称!德州局透视,新道游app辅助器,确实有辅助工具(哔哩哔哩)1、打开软件启动之后找到中间准...