Issue with Initializing DataTable in Angular 18 using `simple-datatables` and `Tailwind CSS`

Discussão em 'Angular' iniciado por patilabhishek394, Setembro 23, 2024.

  1. I am trying to implement a data table using the simple-datatables library in an Angular 18 project. The table is styled with Tailwind CSS, and I have multiple interactive features such as searching and pagination. However, I am encountering an issue where the data table does not initialize correctly, or the table loses functionality when trying to reinitialize after data updates.

    I have implemented the table within my component template and used Tailwind CSS for styling. The data is being fetched and displayed properly, but the DataTable object from the simple-datatables library seems to cause issues with reinitialization.

    Details:

    I am trying to build a table for managing active users, with features such as sorting, searching, and paginating data. Here’s the relevant code:

    HTML Template:

    <table id="active-user-table" class="min-w-full divide-y divide-gray-200">
    <thead class="bg-gray-100">
    <tr>
    <th class="p-4 text-left text-gray-700 font-medium">Sr</th>
    <th class="p-4 text-left text-gray-700 font-medium">Name</th>
    <th class="p-4 text-left text-gray-700 font-medium">Username</th>
    <th class="p-4 text-left text-gray-700 font-medium">Email</th>
    <th class="p-4 text-left text-gray-700 font-medium">Role</th>
    <th class="p-4 text-left text-gray-700 font-medium">Active</th>
    <th class="p-4 text-left text-gray-700 font-medium">Status</th>
    <th class="p-4 text-left text-gray-700 font-medium">Created On</th>
    <th class="p-4 text-left text-gray-700 font-medium">Actions</th>
    </tr>
    </thead>
    <tbody class="bg-white divide-y divide-gray-200">
    <tr *ngIf="users.length === 0">
    <td colspan="100%" class="p-4 text-center text-gray-500">No active users found.</td>
    </tr>
    <tr *ngFor="let user of users; let i = index">
    <td class="p-4 text-gray-600">{{ i + 1 }}</td>
    <td class="p-4 text-gray-600">{{ user.name }}</td>
    <td class="p-4 text-gray-600">{{ user.userName }}</td>
    <td class="p-4 text-gray-600">{{ user.email }}</td>
    <td class="p-4">
    <span [ngClass]="getRoleClass(user.roleId)">
    {{ getRoleName(user.roleId) }}
    </span>
    </td>
    <td class="p-4 text-gray-600">{{ user.isActive ? 'Active' : 'Inactive' }}</td>
    <td class="p-4 text-gray-600">{{ user.isLocked ? 'Locked' : 'Unlocked' }}</td>
    <td class="p-4 text-gray-600">{{ user.createdOn }}</td>
    <td class="p-4 flex">
    <button
    class="bg-amber-500 text-white text-xs p-2 rounded-md hover:bg-amber-700"
    title="{{ user.isLocked ? 'Unlock User' : 'Lock User' }}"
    (click)="toggleLock(user.id)"
    >
    <i class="fa-solid fa-key"></i>
    </button>
    </td>
    </tr>
    </tbody>
    </table>


    Component TypeScript:

    import { Component, AfterViewInit, OnDestroy } from '@angular/core';
    import { DataTable } from 'simple-datatables';
    import { ActiveUsersService } from './services/active-users.service';
    import { LoaderService } from '../../../../shared/services/loader.service';

    @Component({
    selector: 'app-active-users',
    templateUrl: './active-users.component.html',
    styleUrls: ['./active-users.component.css'],
    })
    export class ActiveUsersComponent implements AfterViewInit, OnDestroy {
    users: any[] = [];
    dataTable: DataTable | undefined;

    constructor(private activeUsersService: ActiveUsersService, private loaderService: LoaderService) {}

    ngOnInit() {
    this.fetchUsers();
    }

    fetchUsers() {
    this.activeUsersService.getActiveUsers().subscribe((data) => {
    this.users = data;
    this.initializeDataTable();
    });
    }

    initializeDataTable(): void {
    const tableElement = document.getElementById('active-user-table');
    if (tableElement) {
    if (this.dataTable) {
    this.dataTable.destroy(); // To avoid multiple initializations
    }
    this.dataTable = new DataTable(tableElement as HTMLTableElement, {
    searchable: true,
    perPage: 10,
    });
    }
    }

    ngAfterViewInit() {
    this.initializeDataTable();
    }

    ngOnDestroy() {
    if (this.dataTable) {
    this.dataTable.destroy();
    }
    }

    toggleLock(userId: number) {
    this.message = 'Do you want to lock/unlock this user?';
    this.userIdToLockUnlock = userId;
    this.showLockunlockConfirmationDialog = true;
    }
    }


    Problem:

    Reinitialization Issue: The table doesn't properly reinitialize when new data is fetched.

    Losing DataTable Functionality: When updating the data or navigating between pages, the DataTable library seems to lose its sorting, searching, or pagination functionality.

    What I've Tried: Using DataTable.destroy() to remove the instance before reinitializing. Confirming that the table element is correctly rendered in the DOM before calling new DataTable().

    Expected Outcome: The data table should initialize with full functionality (sorting, searching, pagination), and should reinitialize cleanly after data updates.

    Continue reading...

Compartilhe esta Página