Using Datatable.net with Angular 6 for Change Monitoring

I've been encountering several issues with the custom datatable component that I created.

One specific problem is that when I delete a row from my datatable, not only does the row disappear, but also the pagination functionality and other features stop working properly.

My suspicion is that this issue stems from loading the data after the datatable has already been initialized.

To resolve this, I'm trying to instantiate the Datatable component once the data has been fetched. Here's what I'm attempting:

export class DatatableComponent implements AfterViewInit, OnDestroy, OnInit {
  dataTable: any;
  @ViewChild('dt') private dataTableRef: any;

  @Input() responseModelObservable: Observable<any>;

  constructor(private modalService: NgbModal, private cdr: ChangeDetectorRef) { }

  ngOnInit() {
    this.modelConfig = datatableConfig[this.modelTypeName];
    this.initializeColumns();
  }

  ngAfterViewInit(): void {

    // TODO: need to cleanup to cater for rerendering
    // this.tableBody.changes.subscribe(t => {
    //   if (this.hasRenderedTable !== true && this.tableBody.length !== 0) {
    //     this.initializeDtOptions();
    //     this.dtTrigger.next();
    //     this.hasRenderedTable = true;
    //   }
    // });
  }

  private initializeColumns() {
    this.responseModelObservable.subscribe(x => {
        ...

        //detect if data changed:
        this.cdr.detectChanges();

        //Initialize datatable:
        this.dataTableRef.DataTable();

      } else {
        this.hasData = false;
      }
    });
  }
}

The code above is resulting in the following error:

_this.dataTableRef.datatableConfig is not a function

How can I properly instantiate the Datatable component after the data has finished loading?

Answer №1

datatable.net has some limitations when used with Angular as it does not bind the data automatically. Instead, you need to utilize event handlers such as:

datatable.on('init', () => {})

Make sure to hook into these handlers for proper functionality.

For a more seamless solution, consider switching from datatable.net to devextreme or ag-grid. Both of these alternatives offer better binding capabilities and have plenty of Angular-specific examples available.

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

create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Pl ...

Can we determine the return type of a function based on the specific parameters it is called with?

When working with generated APIs, such as openapi-fetch, our code may look something like this: import {paths} from "./the-generated-types"; import createClient from "openapi-fetch"; const client = createClient<paths>(); // U ...

Creating a composite object in Angular 2 reactive forms: a step-by-step guide

These are the two classes I have: export class Machine { name = ''; computer = new Computer() } export class Computer { os = ''; } Then in my component, using reactive forms, I have: ngOnInit() { this.form = this.fb ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

Guide to seamlessly incorporate a HTML template into your Angular 7 project

I'm currently in the process of integrating an HTML template into my Angular 7 project, and unfortunately, it does not seem to be functioning as expected. To start off, I have placed the template files under assets/template/.. and included the necess ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

Check for mobile browser without having to refresh the page

Currently, I am facing an issue with closing the sidebar when the user clicks on Click Me button in mobile view using flexbox layout. The problem arises because the page needs to be refreshed for it to recognize if it's in mobile mode or not by utiliz ...

Employing a section of an intricate map found in the Stores React platform

Take a look at this data stored in Zustand or any other store. productMap: { 'product-id-abc': { info: { name: 'Gmail', url: 'gmail.com', api: 'localhost:8080' }, endpo ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

The Angular2 application was constructed using angular-cli, incorporating a directive, and optimized with the ng build

I am working on an angular-cli app and my environment details are: npm -v 3.10.8 node -v v6.9.1 angular2 ^2.4.0 angular/cli 1.0.0-beta.32.3 Recently, I added the following line to my package.json: "angular2-auto-scroll": "1.0.12" You can find more info ...

Incorporating Angular 6 and NodeJS 8.4 with the MEAN stack, I aim to display the current status of all identifiers stored in MongoDB directly onto the browser

After successfully storing the list of objects in MongoDB, I have implemented a functionality to display all items on the browser. When the inventory button is clicked, the routerlink is used to fetch the availability and list them accordingly. Now, I am ...

Tips for customizing colors for dynamically added bars in an Angular bar chart

Here is a sample of my chart: Check out the chart By clicking the change data button, I am adding a new bar to the chart. Is there a way to change only the color of the newly added bar? Is it possible to achieve this? ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Issue in TypeScript: The module "*.svg" does not have a component that is exported named "ReactComponent"

I'm attempting to bring in an .svg file as a React component using TypeScript. As per the React documentation, the process should look like this: import { ReactComponent as Icon } from './Icon.svg'; Referring to the TypeScript documentati ...

Issue with Angular trackBy not functioning properly within a nested *ngFor loop

My component is similar to the following <div class="users-list" *ngIf="datasetPermission !== undefined"> <div *ngFor="let userpermission of datasetPermission; trackBy : trackByFn"> <span *ngFor="let user of userpermission.users"& ...

Getting started with Angular 2 using NPM version 3.10.6 and Angular CLI 1.0.0

I am having trouble when I run 'NPM start,' all I get is https://i.sstatic.net/QCViF.png Below are the files in my project: package.json { "name": "angular2-quickstart", "version": "1.0.0", // rest of the package.json file continues... } ...

Pull in a component from another repository

I recently established a repository in bitbucket named "angular-lister". The layout of the repository can be viewed https://i.sstatic.net/bDANV.png. Subsequently, I created another repository with a similar structure, although I cannot display an image he ...

The issue of losing context when using Papaparse with an Angular 4 function

Check out this block of code httpcsv2Array(event) { var gethttpcsv = Papa.parse('https://docs.google.com/spreadsheets/d/e/yadyada/pub?output=csv', { download: true, header: true, ...

Create a dynamic Prisma data call by using the syntax: this.prisma['dataType'].count()

I'm currently working on implementing a counting function that can be utilized in all of my objects. In my 'core' file, Prisma is involved in this process. This allows me to execute commands like this.user.count() or this.company.count() I ...

What could be the reason that my Bootstrap dropdown menu is not appearing on my website

I am currently utilizing Angular in my project. I have incorporated bootstrap and jQuery via NPM install, and specified them as dependencies in angular.json. The navbar on my site contains a dropdown menu. When I hover over the dropdown menu, it should di ...