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

相关内容

热门资讯

透视步骤!聚星ai辅助工具激活... 透视步骤!聚星ai辅助工具激活码,poker辅助器免费安装(透视)一直是真的挂(哔哩哔哩)1、透视步...
透视经验!wpk有辅助器吗,w... 透视经验!wpk有辅助器吗,wepoker免费脚本(透视)总是是真的挂(哔哩哔哩)一、wepoker...
透视绝活儿!wpk辅助是什么,... 透视绝活儿!wpk辅助是什么,wpk透视插件(透视)一直是真的脚本脚本(哔哩哔哩)1)wpk辅助是什...
透视积累!wepoker高级辅... 透视积累!wepoker高级辅助,大菠萝手游辅助(透视)切实真的有挂(哔哩哔哩)1、每一步都需要思考...
透视烘培!wepokerplu... 透视烘培!wepokerplus透视脚本免费,德州圈脚本(透视)真是存在有挂(哔哩哔哩)透视烘培!w...
透视阶段!wepokerh5破... 透视阶段!wepokerh5破解,wepoker永久免费脚本(透视)总是真的是有挂(哔哩哔哩)1、任...
透视课程!wepoker钻石怎... 透视课程!wepoker钻石怎么看底牌,wepoker有透视吗(透视)一贯真的是有透视神器(哔哩哔哩...
透视总结!pokemmo辅助官... 透视总结!pokemmo辅助官网,wepoker私人局可以透视(透视)本来是有挂(哔哩哔哩)1、we...
透视指引!pokemmo辅助器... 透视指引!pokemmo辅助器手机版下载,福建大菠萝万能辅助器(透视)本来是有挂(哔哩哔哩)该软件可...
透视大纲!cloudpoker... 透视大纲!cloudpoker怎么开挂,hhpoker怎么破解(透视)其实存在有挂(哔哩哔哩)clo...