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

相关内容

热门资讯

透视专业!wepoker祈福有... 透视专业!wepoker祈福有用吗,wepokerplus辅助-一直存在有辅助技巧(哔哩哔哩)1. ...
透视科普!aapoker怎么设... 透视科普!aapoker怎么设置抽水,aapoker辅助怎么用-一贯是真的有辅助插件(哔哩哔哩)1、...
透视总结!hhpoker万能辅... 透视总结!hhpoker万能辅助器,hhpoker德州机器人-果然真的有辅助app(哔哩哔哩)1、破...
透视详情!wepoker辅助器... 透视详情!wepoker辅助器激活码,htx矩阵wepoker辅助-确实存在有辅助教程(哔哩哔哩)1...
透视科普!wepoker模拟器... 透视科普!wepoker模拟器哪个好用,淘宝买wepoker透视有用吗-切实一直总是有辅助神器(哔哩...
透视有挂!wepoker免费透... 透视有挂!wepoker免费透视,wepoker智能辅助插件-好像是有辅助神器(哔哩哔哩)透视方法中...
透视必备!wepoker透视脚... 透视必备!wepoker透视脚本苹果版,wepoker提高好牌率-本来一直总是有辅助脚本(哔哩哔哩)...
透视普及!wejoker辅助器... 透视普及!wejoker辅助器怎么卖,购买wepoker模拟器-好像一直总是有辅助脚本(哔哩哔哩)1...
透视普及!hhpoker真的假... 透视普及!hhpoker真的假的,hhpoker视频巡查真的假的-好像真的有辅助神器(哔哩哔哩)小薇...
透视必备!hhpoker免费辅... 透视必备!hhpoker免费辅助器,hhpoker真的有透视吗-一直有辅助app(哔哩哔哩)小薇(辅...