我在主视图中有一个带有停靠功能的侧边导航和一个数据表。取消停靠侧边导航后,主视图中的数据表不会重新计算(这将留下侧边导航来自的一些空白空间)因此我需要在单击时手动重新计算。然而,问题在于侧边导航和数据表是两个不同的指令。
附言。我有多个具有不同数据表名称的模块
同样的问题: 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/