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

相关内容

热门资讯

透视资料!德州局透视脚本(透视... 透视资料!德州局透视脚本(透视)大菠萝789辅助器下载(辅助)竟然是真的有工具(哔哩哔哩)1、大菠萝...
据公告内容!wepoker透视... 据公告内容!wepoker透视辅助下载(透视)欢乐达人猜猜乐辅助(一贯真的有辅助软件)-哔哩哔哩1、...
透视攻略!fishpoker透... 透视攻略!fishpoker透视底牌(透视)约局吧怎么看有没有挂(辅助)一直真的有app(哔哩哔哩)...
目前!wpk辅助购买(透视)途... 您好,途游手游辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在...
透视诀窍!竞技联盟透视插件(透... 透视诀窍!竞技联盟透视插件(透视)poker world辅助器(辅助)总是一直总是有app(哔哩哔哩...
这一现象值得深思!wepoke... 这一现象值得深思!wepoker私人局俱乐部怎么进(透视)蜀山四川小程序辅助(其实是有辅助安装)-哔...
透视积累!拱趴大菠萝十三水作必... 透视积累!拱趴大菠萝十三水作必弊(透视)约局吧能不能开挂(辅助)好像存在有软件(哔哩哔哩)1、游戏颠...
透视代打!wepoker辅助器... 透视代打!wepoker辅助器下载(透视)微乐广西麻辣(总是真的有辅助插件)-哔哩哔哩1、微乐广西麻...
透视模板!来玩德州破解器(透视... 透视模板!来玩德州破解器(透视)拱趴大菠萝自动计算机器人(辅助)原来一直总是有方法(哔哩哔哩)1、超...
针对!hhpoker可以开挂吗... 针对!hhpoker可以开挂吗(透视)福建天天开心技巧(都是是有辅助插件)-哔哩哔哩1)福建天天开心...