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

相关内容

热门资讯

热点讨论!aapoker免费透... 热点讨论!aapoker免费透视脚本(辅助挂)一直真的是有挂(确实有挂)1、首先打开aapoker免...
我来分享!hhpoker德州牛... 我来分享!hhpoker德州牛仔视频(辅助挂)果然真的有挂(有挂技巧)1、超多福利:超高返利,海量正...
科技介绍!wepoker怎么获... 科技介绍!wepoker怎么获得好牌(辅助挂)原来真的是有挂(有挂存在)1、金币登录送、破产送、升级...
让我来分享经验!wepoker... 让我来分享经验!wepoker透视器免费(辅助挂)确实是有挂(有挂教学)1、全新机制【wepoker...
热门推荐!hhpkoer辅助器... 热门推荐!hhpkoer辅助器视频(辅助挂)果然有挂(有挂透明挂)1、热门推荐!hhpkoer辅助器...
记者揭秘!wepoker透视功... 记者揭秘!wepoker透视功能下载(辅助挂)其实是真的有挂(有挂辅助)1、wepoker透视功能下...
玩家必备科技!wepoker买... 玩家必备科技!wepoker买钻石有用吗(辅助挂)切实存在有挂(确实有挂)1、wepoker买钻石有...
必知教程!werplan透视挂... 必知教程!werplan透视挂(辅助挂)原来真的有挂(确实有挂)1、下载好werplan透视挂脚本下...
记者揭秘!pokemmo脚本(... 记者揭秘!pokemmo脚本(辅助挂)原来真的是有挂(有挂详细)1、pokemmo脚本免费辅助多个强...
实测分享!wepoker透视有... 实测分享!wepoker透视有没有(辅助挂)确实真的有挂(今日头条)1、实测分享!wepoker透视...