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

相关内容

热门资讯

七分钟普及!福建十三水辅助插件... 七分钟普及!福建十三水辅助插件,欢乐驿站可以开挂,教你攻略(有挂秘籍)是一款可以让一直输的玩家,快速...
发现一款!aapoker插件,... 发现一款!aapoker插件,wpk德州ai机器人其实真的有挂,德州教程(有挂详情)-哔哩哔哩关于w...
记者爆料(Wepoke代码)外... 记者爆料(Wepoke代码)外挂透视辅助app(透视)软件透明挂(2025已更新)(哔哩哔哩)是一款...
玩家必用!欢乐棋牌有挂吗(辅助... 玩家必用!欢乐棋牌有挂吗(辅助挂)原来真的有挂2025已更新)(哔哩哔哩)1、不需要AI权限,帮助你...
4分钟攻略!微信海南麻将小程序... 4分钟攻略!微信海南麻将小程序插件购买(透视)外挂透视辅助器安装(2020已更新)(哔哩哔哩)是一款...
透视挂!aapoker有后台操... 透视挂!aapoker有后台操控(德扑之星有辅)外挂透明挂辅助器安装(辅助挂)新版2024教程(20...
揭秘几款(Wepoke游戏)外... 揭秘几款(Wepoke游戏)外挂透明挂辅助工具(透视)曝光教程(2021已更新)(哔哩哔哩);致您一...
记者发布!微扑克发牌规律性(透... 记者发布!微扑克发牌规律性(透视)外挂透明挂辅助器安装(2021已更新)(哔哩哔哩)是一款可以让一直...
两分钟攻略!约战竞技场能开挂,... 两分钟攻略!约战竞技场能开挂,广东雀神辅助器免费版,wpk教程(有挂神器)是一款可以让一直输的玩家,...
关于!aa扑克能用模拟器,wP... 关于!aa扑克能用模拟器,wPK原来真的有挂,爆料教程(有挂透明)-哔哩哔哩相信很多朋友都在电脑上玩...