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

相关内容

热门资讯

透视ios!wepoker安装... 透视ios!wepoker安装教程(透视)开挂辅助工具(本来真的是有挂)-哔哩哔哩1、超多福利:超高...
透视教程!sohoo开挂辅助,... 透视教程!sohoo开挂辅助,wepoker公共底牌,手筋教程(确实是有挂)-哔哩哔哩一、wepok...
透视自建房!佛手在线大菠萝技巧... 透视自建房!佛手在线大菠萝技巧(透视)开挂辅助神器(一贯是真的挂)-哔哩哔哩佛手在线大菠萝技巧是一种...
透视规律!wpk私人局辅助是真... 透视规律!wpk私人局辅助是真的吗,wepoker网页版透视方法,指南教程(原来真的有挂)-哔哩哔哩...
透视必备!黑侠破解wepoke... 透视必备!黑侠破解wepoker(透视)开挂辅助方法(原来真的是有挂)-哔哩哔哩黑侠破解wepoke...
透视辅助!wepoker底牌透... 透视辅助!wepoker底牌透视,wpk透视是真的吗,资料教程(好像是真的挂)-哔哩哔哩1、实时wp...
透视神器!wepoker破解是... 透视神器!wepoker破解是真的还是假的(透视)开挂辅助方法(原来真的是有挂)-哔哩哔哩进入游戏-...
透视app!sohoo竞技联盟... 透视app!sohoo竞技联盟辅助器,wepoker透视脚本免费使用视频,教程书教程(本来存在有挂)...
透视胜率!we poker辅助... 透视胜率!we poker辅助器v3.3(透视)开挂辅助方法(本来存在有挂)-哔哩哔哩一、we po...
透视总结!wpk真的有透视嘛,... 透视总结!wpk真的有透视嘛,epoker透视,方案教程(原来是真的挂)-哔哩哔哩1、上手简单,内置...