Discover the steps to update the rows, adjust the number of results, and manage pagination in angular-datatable with an observable as the primary data source

Incorporating angular-datatables into my Angular 7 application has been a challenge, especially when it comes to displaying search results efficiently.

Within the request-creation-component, a search form is generated. Upon clicking the submit button, an HTTP Post request is dispatched to the backend via a request-service. Subsequently, an observable in the request-service is updated, which the request-result-component subscribes to.

The issue I'm encountering lies in the fact that the datatable used to showcase the results fails to refresh its rows, result count, and pagination buttons when new data is received.

Despite receiving new results, the datatable continues to display the initial set of rows, result count, and pagination controls.

The code in the request-result-component:


requestResponse;
resultsAreFound = true;
constructor(private requestService: RequestService) { }
public dataTable: DataTable;

ngOnInit() {
        this.dataTable =  {headerRow : null, footerRow: null, dataRows: null };

        this.requestService.currentSearchResult.subscribe(result => {
            this.requestResponse = result;
            if (result.length > 0) {
            this.resultsAreFound = true;
             // If new results are obtained, update the datatable with the fresh data.
                this.dataTable.headerRow = Object.keys(this.requestResponse[0]);
                this.dataTable.footerRow = Object.keys(this.requestResponse[0]);
                this.dataTable.dataRows = this.requestResponse.map(function(i: { [s: string]: {}; } | ArrayLike<{}>) {
                        return Object.values(i);
                    });
            } else {
                // In case of empty results, hide the datatable and display a "0 results" message.
                this.resultsAreFound = false;
            }
         });
        }

ngAfterViewInit() {
        $('#datatable').DataTable({
            'pagingType': 'full_numbers',
            'lengthMenu': [
                [10, 25, 50, -1],
                [10, 25, 50, 'All']
            ],
            responsive: true,
            language: {
                search: '_INPUT_',
                searchPlaceholder: 'Search records',
            }
        });

The template for the request-result-component:

<div class="main-content" style="margin-top: 50px;">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                  <div [hidden]="resultsAreFound" class="card-header">
                    <h4 class="card-title">0 Results Found.</h4>
                  </div>
                    <div [hidden]="!resultsAreFound" class="card-body">
                        <div class="toolbar">
                        </div>
                          <table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                      <th>{{ dataTable.headerRow[0] }}</th>
                                      <th>{{ dataTable.headerRow[1] }}</th>
                                      <th>{{ dataTable.headerRow[2] }}</th>
                                      <th>{{ dataTable.headerRow[3] }}</th>
                                      <th>{{ dataTable.headerRow[4] }}</th>
                                      <th class="disabled-sorting text-right">{{ dataTable.headerRow[5] }}</th>
                                    </tr>
                                </thead>
                                <tfoot>
                                    <tr>
                                      <th>{{ dataTable.footerRow[0] }}</th>
                                      <th>{{ dataTable.footerRow[1] }}</th>
                                      <th>{{ dataTable.footerRow[2] }}</th>
                                      <th>{{ dataTable.footerRow[3] }}</th>
                                      <th>{{ dataTable.footerRow[4] }}</th>
                                      <th>{{ dataTable.footerRow[5] }}</th>
                                    </tr>
                                </tfoot>
                                <tbody>
                                    <tr *ngFor="let row of dataTable.dataRows">
                                        <td>{{row[0]}}</td>
                                        <td>{{row[1]}}</td>
                                        <td>{{row[2]}}</td>
                                        <td>{{row[3]}}</td>
                                        <td>{{row[4]}}</td>
                                        <td class="text-right">
                                          <a href="#" class="btn btn-danger btn-link btn-icon btn-sm remove"><i class="fa fa-times"></i></a>
                                        </td>

                                    </tr>
                                </tbody>
                            </table>
                    </div>
                    <!-- end content-->
                </div>
                <!--  end card  -->
            </div>
            <!-- end col-md-12 -->
        </div>
        <!-- end row -->
</div>




Answer №1

The angular-datatable (angular library for datatables.net) does not provide support for dynamic data sources, meaning that once the table is created, the data cannot be changed.

To address this issue, I had to recreate the table every time the data was modified.

Below is the code snippet from the request-results.component.ts file:

import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild } from '@angular/core';
import { RequestService } from '../services/request.service';
import { Subject } from 'rxjs/internal/Subject';
import { DataTableDirective } from 'angular-datatables';

// Other imports...

@Component({
    selector: 'app-request-results',
    templateUrl: './request-results.component.html'
})

export class RequestResultsComponent implements OnDestroy, AfterViewInit, OnInit {

@ViewChild(DataTableDirective)
dtElement: DataTableDirective;

// Additional component properties and methods...

and here is the content of the request-results.component.html file:

<div class="main-content" style="margin-top: 50px; padding-left: 0px; padding-right: 0px">
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <!-- Card content structure -->
        </div>
    </div>
</div>

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

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...

The Node.js application successfully operates on a local environment, however encounters issues when attempting to run on docker resulting in an error message stating "sh

Despite successfully building the docker image, I am facing difficulties getting the container to run. Below is the content of the package.json file: { "name": "linked-versions-viewer", "version": "1.0.0", &quo ...

Setting up Typescript classes that inherit from one another with diverse properties for each subclass

I'm fairly new to Typescript and currently grappling with how to effectively manage class inheritance when base classes have distinct properties. Essentially, I have a base class where I aim to define shared functionality and a series of subclasses w ...

Utilizing TypeScript's generic constraints for multiple primitive data types

Consider the following function: myFunc(object: string | null): string | null {} The desired behavior for this function is to return type string when the object parameter is of type string, and return type string | null when the object parameter is of ty ...

What is the best way to insert a placeholder React element into a different Component using TypeScript?

I've encountered a Typescript error that has me stumped. Check out the code snippet below: interface AppProps { Component: JSX.ElementClass; pageProps: JSX.ElementAttributesProperty; } const App = ({ Component, pageProps }: AppProps) => { co ...

Obtaining information from an API using Angular

I am currently working on extracting data from various API's and I am encountering some difficulties. The initial part is functioning correctly, with the code provided below : ngOnInit(): void { this.http.get('http://.../api/getData?table=ge ...

Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page: https://i.stack.imgur.com/qigTr.png Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionC ...

Unable to find a solution to Angular response options

I'm having trouble saving an item to local storage when receiving a 200 response from the backend. It seems like the request status is not being recognized properly. options = { headers: new HttpHeaders({ 'Content-Type': &apos ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

What steps can be taken to establish an array type that is limited to predefined values?

I am currently working on defining a type for an array that requires specific values to be present in a certain order at the beginning of the array. type SpecificArray = ('hello'|'goodbye'|string)[] // Current const myArray: SpecificAr ...

Sass-loader in Webpack fails to recognize the use of '@' symbol and raises an error

I am facing an issue with loading a SCSS file through webpack. It seems like many others are experiencing the same problem without any clear explanation. Essentially, I am encountering this error: ERROR in ./src/app/theme.scss Module parse failed: C:&bso ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

Error message displayed in console due to AJV JSON schema validation when the maximum character limit is exceeded

In this provided example: { "default": "adsds", "max": 1 } I attempted to reference the dynamically provided 'max' value and validate the number of characters entered in the 'default' field. To achieve ...

When trying to use ngModel with Angular, an error occurs where the property 'selected' cannot be created on a string

I'm currently attempting to utilize [(ngModel)] in the following manner: <div class="items"> <tbody> <tr *ngFor="let info of this.information"> <td> <input type="checkbox" [(ngModel)]="this.info.n ...

Is it possible to set up tsc to compile test specifications specifically from a designated directory?

I have been working on integrating e2e tests into an Angular project that was not originally set up with @angular-cli, so I have been manually configuring most of it. Currently, I am trying to define a script in the package.json file to transpile only the ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

The bespoke node package does not have an available export titled

No matter what I do, nothing seems to be effective. I have successfully developed and launched the following module: Index.ts : import ContentIOService from "./IOServices/ContentIOService"; export = { ContentIOService: ContentIOService, } ...

Why is my Angular proxy failing to rewrite the path when making an HTTP GET request?

I am facing an issue with my proxy configuration where it is not redirecting as expected based on the rewrite configuration. You can find my proxy.config.json below: { "/sap": { "target" : "http://server.domain.com:8002", "secure" : fa ...