网站搜索

javascript - Angular 仅当元素超出视口时显示 - 修复 ExpressionChangedAfterItHasBeenCheckedError


我正尝试在表格超过视口时,在表格底部显示第二个分页器。然而,我总是遇到 ExpressionChangedAfterItHasBeenCheckedError 错误。我尝试过使用 ChangeDetectorRef、带有 HostListener 的 onResize 属性,但似乎总是出现不同的错误。我希望有人能帮我找到解决这个问题的“Angular方式”。

这是我的模板:

...
<div #tableContainer class="table-container">
    <table mat-table [dataSource]="messages" class="messages">
      [...]
    </table>
</div>

<mat-toolbar *ngIf="isOutOfViewport(tableContainer)" class="toolbar">
  <mat-toolbar-row>
    <app-manual-paginator class="paginator"
                          [length]="resultCount"
                          [(pageSize)]="pageSize"
                          [pageSizeOptions]="[25, 50, 75, 100]"
                          [(pageIndex)]="page"
                          [showFirstLastButtons]="true"
                          (changePage)="changePage()">
    </app-manual-paginator>
  </mat-toolbar-row>
</mat-toolbar>
...

我调用的组件内部的方法:

public isOutOfViewport(element: Element): boolean {
  const bounds = getViewportOutOfBounds(element);
  return bounds.top || bounds.bottom;
}

以及用于查找边界的工具方法(从在线指南获取:https://gomakethings.com/how-to-check-if-any-part-of-an-element-is-out-of-the-viewport-with-vanilla-js/):

export function getViewportOutOfBounds(element: Element): Bounds {

    // Get element's bounds
    const bounds = element.getBoundingClientRect();

    // Check if it's out of the viewport on each side
    const out: Bounds = {
    top: undefined,
    bottom: undefined,
    left: undefined,
    right: undefined,
    any: undefined,
    all: undefined
  };
    out.top = bounds.top < 0;
    out.left = bounds.left < 0;
    out.bottom = bounds.bottom > (window.innerHeight || document.documentElement.clientHeight);
    out.right = bounds.right > (window.innerWidth || document.documentElement.clientWidth);
    out.any = out.top || out.left || out.bottom || out.right;
    out.all = out.top && out.left && out.bottom && out.right;

    return out;
};

我已经验证过这些方法确实可以单独工作,但在这种情况下我似乎无法让它正常工作。