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

相关内容

热门资讯

透视脚本!wejoker手机版... 透视脚本!wejoker手机版透视脚本,wepoker怎么看牌型(都是真的是有挂)进入游戏-大厅左侧...
透视最新!wpk辅助器是真的吗... 透视最新!wpk辅助器是真的吗,wpk显示有作弊,教你攻略(好像是有挂);一、wpk辅助器是真的吗软...
透视app!wepoker有辅... 透视app!wepoker有辅助功能吗,wepoker透视脚本是什么(真是存在有挂)1、金币登录送、...
透视私人局!wpk透视是真的假... 透视私人局!wpk透视是真的假的,wpk透视辅助方法,解密教程(都是是有挂)运wpk透视是真的假的辅...
透视透视!wepoker怎么买... 透视透视!wepoker怎么买辅助,wepoker私人局规律(真是是有挂);1、wepoker私人局...
透视数据!wpk免费辅助,wp... 透视数据!wpk免费辅助,wpk德州局透视,AI教程(总是是有挂)1、wpk德州局透视透视辅助简单,...
透视透视!wepoker钻石怎... 透视透视!wepoker钻石怎么看底牌,wepoker黑侠辅助器(好像是有挂);wepoker钻石怎...
透视透视挂!wepoker免费... 透视透视挂!wepoker免费透视,wepoker私人局辅助器怎么用(都是存在有挂)1、实时wepo...
透视脚本!wpk作弊,wpk系... 透视脚本!wpk作弊,wpk系统是否存在作弊行为,解说技巧(果然有挂)1)wpk系统是否存在作弊行为...
透视透视!wepoker透视版... 透视透视!wepoker透视版下载,wepoker脚本下载(其实是有挂);1、用户打开应用后不用登录...