This solution utilizes the MutationObserver
to monitor style changes in the left menu and adjust the width of the DatatableComponent
accordingly.
@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();
}
}
The modification required in the markup is minimal:
<ngx-datatable sidePanelToggle ...