Update ngx-datatable when the user clicks on a different directive

My issue involves a Side Navigation with a docking feature and a data table in the Main View. When I undock the side navigation, the data table does not recalculate automatically, leaving empty space where the Side Navigation was. This requires me to manually trigger a recalculation upon click. The challenge is that the Side Navigation and Data Table are separate directives.

Additionally, I have multiple modules with different data table names.

I am facing a similar problem as described here: https://github.com/swimlane/ngx-datatable/issues/193#issuecomment-334809144

Answer №1

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 ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

The dimensions of the pop-up window in Chrome's JavaScript are not displaying correctly

My goal is to launch a new chat room window on our website. The dimensions of the chat room are set to 750px x 590px. Below is the link I am using to trigger the javascript popup. <a href="javascript:void(0)" onclick="window.open('http://gamersuni ...

Is it feasible to invoke a Vue.js function from an Android WebView?

After searching for answers on various sites without success, I am reaching out for help with a specific issue. I am using vuejs with typescript and a webview in an android app. My goal is to have a button in the android app call a vuejs function, and vice ...

What could be causing the error message "setShowModal is undefined" to appear in my React project?

Here is the code snippet I am working on: import React, { useState } from "react"; import Modal from "./Modal"; function displayModal() { setShowModal(true); } export default function NewPostComponent() { const [showModal, setShowMod ...

Navigating between routes in Angular can lead to multiple subscriptions being created

One issue I've encountered is receiving multiple subscriptions as I switch between routes in my Angular application. Within my parent component, I have defined the following routes: <li routerLink="route1" [routerLinkActive]="[&apos ...

Configuring Multer destination dynamically using FormData values in Node.js

I have a scenario where I need to send a file along with some data values using an XMLHttpRequest (xhr) to a Node.js server running Express. To handle multipart data, I am utilizing Multer as bodyParser does not work in this case. router.post("/submit", f ...

Fatal syntax error encountered when attempting to define a JavaScript object

Hey, I'm just starting out with JavaScript and I'm encountering a syntax error with the getValue() function in the code below. Can someone please assist me in solving it? let obj = { x:1, function getValue(){ console.log("hello") } } ...

Error encountered when attempting to close a MatDiaLog in Angular as the close button is unable to read the property 'close' of null

Looking to develop a component that incorporates multiple content projects in angular 6. Here's the code I used in app.component.html: <popup> <button buttonTrigger mat-button><span >Open the popup!</span></button> ...

Why is it that the resource fails to load in an Angular localhost environment when making an http request?

In the realm of ASP.NET MVC projects lies my creation, a masterpiece utilizing Angular UI components powered by ASP.NET WebAPI. As an explorer navigating the unknown territory of Angular, I present to you the sacred texts residing within my project. Behol ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

Click event not triggering for selected option in jQuery dropdown menu

After adding dropdown anchor tags dynamically to the drop-down menu, the click event does not seem to be firing. Do I need to re-bind the click handler after using .append, or should I wrap the click handler in a function? <script src="https://code.jqu ...

Implement a default dropdown menu that displays the current month using Angular and TypeScript

I am looking to implement a dropdown that initially displays the current month. Here is the code snippet I have used: <p-dropdown [options]="months" [filter]="false" filterBy="nombre" [showClear] ...

Tips for personalizing and adjusting the color scheme of a menu in ant design

I am currently working on a website using reactJs and ant design. However, I have encountered an issue with changing the color of a menu item when it is selected or hovered over. Here's the current menu: Menu Image I would like to change the white col ...

Obtaining the value of dynamic checkboxes in Ionic 2

My goal is to populate checkboxes from a database and allow users to complete the checkbox form before submitting it back to the database. However, I am struggling to capture the values of dynamically populated checkboxes in my code snippet below. expor ...

The Bootstrap/Angular tab list items are generated dynamically based on the API response, leading to issues with the DOM

In one of my Angular templates, I have the following snippet. It consists of Bootstrap 3 tabs, but the tab list items (links) are generated dynamically after receiving a response from the API. <ul class="nav nav-tabs pull-right" role="tablist"> &l ...

Seeking a way to keep the returned Ajax string consistent and prevent it from fading away after page transition

I have a form that appears when the user clicks on the "Edit" link, allowing them to input their profile information. Upon submission, the data is processed via Ajax and saved in an SQL database using a PHP script. After saving the new profile, I would lik ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

What steps should I follow to implement Cypress in an older project?

Looking to automate a project built with Node.js version 8.9.4 and an older version of Angular using Cypress for testing, but running into compatibility issues with the current version of Cypress. Is there a way to use an older version of Cypress in this ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...

Using AngularJS to bind to the 'src' property of an <img> tag

There is a table on my website with numerous rows, and each row contains a preview image that should appear in the top right corner when the mouse hovers over it. I attempted to insert an image tag with AngularJS binding for the URL in the src attribute l ...