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

相关内容

热门资讯

透视讲解"hhpok... 透视讲解"hhpoker辅助器视频"哈糖大菠萝怎么开挂(果然真的是有辅助平台)-哔哩哔哩1、金币登录...
截至发稿"wepok... 截至发稿"wepoker破解游戏盒子"wepoker脚本(果然是真的辅助app)-哔哩哔哩所有人都在...
于此同时"poker... 于此同时"poker辅助器免费安装"aapoker安装包怎么使用(确实存在有辅助插件)-哔哩哔哩1、...
透视有挂"竞技联盟辅... 透视有挂"竞技联盟辅助"wepoker怎么看底牌(本来真的有辅助下载)-哔哩哔哩1、wepoker怎...
此事引发广泛关注"w... 此事引发广泛关注"wepoker软件辅助程序"we-poker是什么软件(一贯有辅助平台)-哔哩哔哩...
于此同时"德扑圈透视... 于此同时"德扑圈透视挂"wepoker轻量版书签(一直存在有辅助软件)-哔哩哔哩1、于此同时"德扑圈...
近期"wepoker... 近期"wepoker辅助器官方"wpk官网下载链接(切实存在有辅助插件)-哔哩哔哩wepoker辅助...
据文件显示"wepo... 据文件显示"wepoker透视脚本免费下载pc"epoker透视(本来真的有辅助安装)-哔哩哔哩we...
透视神器"wepok... 透视神器"wepoker私人局辅助挂"wepoker可以透视码(果然真的是有辅助插件)-哔哩哔哩;1...
目前"wepoker... 目前"wepoker黑侠辅助器正版下载"wejoker辅助器要钱玩吗(原来是真的辅助软件)-哔哩哔哩...