【问题标题】:Angular Mat-Table finished rendering Event / Mat Paginator Loading SpinnerAngular Mat-Table 完成渲染事件 / Mat Paginator Loading Spinner
【发布时间】:2020-02-23 20:16:49
【问题描述】:

我正在使用带有相当大的预查询数据源的 Angular 材料表。现在,每次我使用内置的分页器更改表格页面时,我都会在新的表格行呈现之前有一个短暂的延迟,同时我想显示一个加载微调器。

问题是,当 Table-Page 开始更改时,Paginator 只会触发一个事件,到目前为止,我还没有找到解决方案来找出新行完全呈现时。 (这将是我隐藏加载 Spinner 的时刻)

我知道服务器端分页会解决这个问题,但我更喜欢另一种可能性..

对我的问题有什么建议吗?

【问题讨论】:

  • 欢迎来到 SO。请发布您尝试过的代码。

标签: angular angular-material angular-material-table


【解决方案1】:

我这样做的方法是使用(未记录的)“last”局部变量,该变量为表中的最后一行设置为 true。使用它,我将“最后一行”类添加到最后一行中的元素。然后使用 MutationObserver 我检测该元素何时插入 DOM。

即使这基本上是一个池,因为每次 DOM 发生变化时都会执行 MutationObserver 处理程序,但我们能够在最后一行插入 DOM 时执行一段代码。我还没有用 Paginator 尝试过。

看到 ngFor 有它,我想到了使用“最后一个”局部变量,我认为应该将表实现为 ngFor 或者它应该使用一个 ...

<table mat-table [dataSource]="(results$ | async)?.drivers" class="mat-elevation-z8">
<ng-container matColumnDef="colId">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td class="cell-id" mat-cell *matCellDef="let driver; let i = index; let isLastRow = last">
        <div class="no-wrap-ellipsis" [ngClass]="{'last-row': isLastRow}">{{driver.driverId}}</div>
    </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="scheduleTable_displayedColumns; sticky: true;"></tr>
<tr mat-row *matRowDef="let row; columns: scheduleTable_displayedColumns;"></tr>
  protected mutationObserverToDetectLastRow: MutationObserver;

  ngOnInit(): void {
    this.initMutationObserverToDetectLastRow();
  }

  private initMutationObserverToDetectLastRow = () => {
    this.mutationObserverToDetectLastRow = new MutationObserver(_ => this.mutationObserverToDetectLastRowHandler());
    this.mutationObserverToDetectLastRow.observe(document, { attributes: false, childList: true, characterData: false, subtree: true });
  }

  protected mutationObserverToDetectLastRowHandler = () => {
    if (document.body.contains(document.body.querySelector(".last-row"))) {
      console.log("Last row was displayed");
    }

    this.mutationObserverToDetectLastRow.disconnect();
  }

  ngOnDestroy(): void {
    this.mutationObserverToDetectLastRow.disconnect();
  }

【讨论】:

  • 如果我们定期添加新行会怎样?不想使用 setTimeout...
【解决方案2】:

在我看来,更简单的方法是在组件中注入 NgZone 作为依赖项并订阅 onStable observable。

假设您有一个 changePage 函数来处理页面更改。然后你可以这样做:

this.changePage(newPage);
this.zone.onStable.pipe(take(1)).subscribe(() => {
  console.log('Do whatever you want, the table is rendered');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多