【问题标题】:Angular Material Table: Detect what rows (items) are currently being displayedAngular Material Table:检测当前正在显示哪些行(项目)
【发布时间】:2021-08-20 04:40:03
【问题描述】:

我需要一些方法来跟踪材料表中当前正在显示的项目(行)。根据documentation<mat-table> 建立在<cdk-table> 之上,赋予它viewChange 属性。我的理解是,只要显示的行集发生更改,就会触发 BehaviorSubject。例如,可能总共有 400 行,但由于分页,屏幕上只有 20 行。当用户点击进入下一页时,这应该会导致viewChange 发出。有谁知道如何使用这个属性?我尝试了以下代码,但它只触发一次,值为{ start: 0, end: 1.7976931348623157e+308 }

component.ts:

allTasks = new MatTableDataSource<Task>([]);

@ViewChild(MatTable) table: MatTable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sorter: MatSort;

ngAfterViewInit() {
  this.allTasks.paginator = this.paginator;
  this.allTasks.sort = this.sorter;
  this.table.viewChange.asObservable().subscribe(val => {
    console.log(`${val.start} - ${val.end}`);
  });
}

component.html:

<mat-table
  matSort
  [dataSource]="this.allTasks"
>
...
</mat-table>

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    获取显示行的一种方法是使用分页器的订阅并使用 pageIndex 从数据源获取数据。

    allTasks = new MatTableDataSource<Task>([]);
    
    @ViewChild(MatTable) table: MatTable<any>;
    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sorter: MatSort;
    
    ngAfterViewInit() {
      this.allTasks.paginator = this.paginator;
      this.allTasks.sort = this.sorter;
    
      this.allTasks.paginator.page.subscribe((pageEvent: PageEvent) => {
          const startIndex = pageEvent.pageIndex * pageEvent.pageSize;
          const endIndex = startIndex + pageEvent.pageSize;
          const itemsShowed = this.allTasks.filteredData.slice(startIndex, endIndex);
          console.log(itemsShowed);
      });
    
    }
    

    【讨论】:

    【解决方案2】:

    虽然 Daniel 解决方案完美运行,但我发现了一些更简单的方法。

    this.allTasks.connect().value
    

    将为您提供当前页面在屏幕上显示的行。

    如果您想要所有过滤后的行(可能显示在多个页面上),您还可以使用:

    this.allTasks.filteredData
    

    【讨论】:

    • 这可能会在每次调用数据源时创建一个新的订阅 - 所以需要在使用后取消订阅?
    • 我不这么认为,'connect()' 方法返回一个“BehaviorSubject”,如果你订阅它,它会创建一个订阅,但这里我们直接使用“。价值”。所以不需要退订。
    【解决方案3】:

    看起来对 viewChange 的正确支持是 Angular Material 代码中的 TODO 项。这是今天最新版本的摘录。

    // TODO(andrewseguin): Remove max value as the end index
    //   and instead calculate the view on init and scroll.
    /**
     * Stream containing the latest information on what rows are being displayed on screen.
     * Can be used by the data source to as a heuristic of what data should be provided.
     */
    viewChange: BehaviorSubject<{start: number, end: number}> =
        new BehaviorSubject<{start: number, end: number}>({start: 0, end: Number.MAX_VALUE});
    

    并且它从不在组件中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      相关资源
      最近更新 更多