Angular中的BehaviorSubject在使用mattable排序后不能更新UI
创始人
2024-10-31 02:30:32
0

这个问题通常出现在使用mat table进行排序时,由于不直接与数据源进行排序而是与视图数组进行排序,因此可能导致视图数组和原始数据源不同步。解决此问题的方法是在数据更改时更新BehaviorSubject的值,以便更新视图数组。以下是一个示例:

component.ts:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { BehaviorSubject } from 'rxjs';

interface Data {
  name: string;
  position: string;
  age: number;
}

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {

  dataSource = new MatTableDataSource();
  data$: BehaviorSubject = new BehaviorSubject([]);
  displayedColumns: string[] = ['name', 'position', 'age'];
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  constructor() { }

  ngOnInit(): void {
    this.dataSource.sort = this.sort;
    this.data$.subscribe(data => {
      this.dataSource.data = data;
    })
  }

  loadData() {
    const data = [
      { name: 'John', position: 'Developer', age: 25 },
      { name: 'Alice', position: 'Manager', age: 30 },
      { name: 'Bob', position: 'Designer', age: 35 },
      { name: 'Max', position: 'Developer', age: 27 },
    ];
    this.data$.next(data);
  }
}

component.html:


    
    
    

相关内容

热门资讯

透视肯定!aapoker如何设... 透视肯定!aapoker如何设置胜率(透视)免费透视脚本(总是真的是有挂)1、玩家可以在aapoke...
透视好友!德州局透视,拱趴大菠... 透视好友!德州局透视,拱趴大菠萝挂(竟然有挂)1)拱趴大菠萝挂辅助挂:进一步探索拱趴大菠萝挂辅助透视...
透视科技!aapoker辅助怎... 透视科技!aapoker辅助怎么用(透视)透视脚本(竟然存在有挂)1、该软件可以轻松地帮助玩家将aa...
透视科技!pokemmo脚本辅... 透视科技!pokemmo脚本辅助器下载,德州私人局脚本(本来是真的有挂)1、全新机制【pokemmo...
透视规律!aapoker辅助软... 透视规律!aapoker辅助软件合法吗(透视)免费透视脚本(确实存在有挂)1、aapoker辅助软件...
透视系统!pokeplus脚本... 透视系统!pokeplus脚本,约局吧德州真的有透视挂吗(确实真的是有挂)1、约局吧德州真的有透视挂...
透视脚本!aapoker脚本(... 透视脚本!aapoker脚本(透视)脚本(果然真的是有挂);1、进入游戏-大厅左侧-新手福利-激活码...
透视安装!werplan辅助软... 透视安装!werplan辅助软件,智星德州可以透视吗(总是有挂)1、不需要AI权限,帮助你快速的进行...
透视真的!aapoker透视插... 透视真的!aapoker透视插件(透视)插件下载(都是是真的有挂)1、进入游戏-大厅左侧-新手福利-...
透视脚本!poker红龙辅助,... 透视脚本!poker红龙辅助,wepoker安装教程(总是真的有挂)1、下载好wepoker安装教程...
Name {{ row.name }} Position {{ row.position }} Age {{ row.age }}