javascript - 在另一个指令的点击事件上重新计算 ngx-datatable

标签 javascript angular typescript user-interface ngx-datatable

我在主视图中有一个带有停靠功能的侧边导航和一个数据表。取消停靠侧边导航后,主视图中的数据表不会重新计算(这将留下侧边导航来自的一些空白空间)因此我需要在单击时手动重新计算。然而,问题在于侧边导航和数据表是两个不同的指令。

附言。我有多个具有不同数据表名称的模块

同样的问题: https://github.com/swimlane/ngx-datatable/issues/193#issuecomment-334809144

最佳答案

我使用 MutationObserver 实现了它,它跟踪左侧菜单的样式变化并设置 DatatableComponent 宽度。

@Directive({ selector: '[sidePanelToggle]' })
export class SidePanelToggleDirective implements OnDestroy {
  private changes: MutationObserver;
  wasVisible: boolean | undefined;

  constructor(
    private elementRef: ElementRef,
    @Host() @Self() private tableComponent: DatatableComponent
  ) {
    this.changes = new MutationObserver((mutations: MutationRecord[]) => {
        mutations.forEach((mutation: MutationRecord) => {
            const sideNavElement = mutation.target as HTMLElement;
            const tableElement = this.elementRef.nativeElement as HTMLElement;
            const isVisible = sideNavElement?.style.visibility === 'visible';
            if (this.wasVisible === undefined || this.wasVisible && !isVisible || !this.wasVisible && isVisible) {
              if (tableElement.style.width) {
                tableElement.style.width = `${SidePanelToggleDirective.floatOrZero(tableElement.style.width) + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Already set before, now will be ', tableElement.style.width);
              }
              else {
                tableElement.style.width = `${tableElement.offsetWidth + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Setting first time as ', tableElement.style.width);
              }
              this.tableComponent.recalculate();
            }
            this.wasVisible = isVisible;
        });
    });

    document.querySelectorAll('mat-sidenav[position="start"]').forEach(element => {
      this.changes.observe(element, { attributeFilter: ['style'] });
    });
  }

  private static floatOrZero(value: any) {
    const result = parseFloat(value);
    return isNaN(result) ? 0 : result;
  }

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

标记的变化很小:

<ngx-datatable sidePanelToggle ...

关于javascript - 在另一个指令的点击事件上重新计算 ngx-datatable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658199/

相关文章:

javascript - 第二种 form.submit() 在 XP 上的 Safari 中不起作用,在其他浏览器上起作用

php - 有人知道如何在 mysql 中存储图像并使用 Angular 和 php 显示回来吗?

node.js - Froala 编辑器不适用于带有 typescript 的 Angular 4

angular - 如何使用 AngularFirebase 和 Angular 7 从用户集合中获取用户数据

typescript - 移位数组后此条件将始终评估为 false

javascript - 在 CasperJS 中计算给定元素的 XPath

javascript - 将每个数字换行并在前面添加零,最多 X 个数字

javascript - 如何在Facebook共享按钮中使用Angular JS传递URL

angular - Angular5 中具有动态内容的可重用模态

angular - (click) 只在 Chrome 中工作,在其他人中不工作