The Datatable is displaying the message "The table is currently empty" despite the fact that the rows have been loaded through Angular

My experience with displaying a data table in Angular was frustrating. Even though all the records were present in the table, it kept showing "no data available." Additionally, the search function refused to work as intended. Whenever I tried searching for something, it just displayed the message "no data available in table". You can see the issue in this screenshot. enter image description here I had to include dtTrigger.next(); in the afterViewInit function to avoid the error "cannot reinitialize data table."

forum-admin-list.component.ts

    import { Component, OnInit ,OnDestroy,AfterViewInit,ViewChild} from '@angular/core';
    import { AngularFirestore } from '@angular/fire/firestore';
    import { PostService } from 'src/app/shared/post.service';
    import { Post } from 'src/app/shared/post.model';
    import { ToastrService } from 'ngx-toastr';
    import { Subject } from 'rxjs';
    import { DataTableDirective } from 'angular-datatables';

    @Component({
      selector: 'app-forum-admin-list',
      templateUrl: './forum-admin-list.component.html',
      styleUrls: ['./forum-admin-list.component.css']
    })
    export class ForumAdminListComponent implements OnInit,OnDestroy,AfterViewInit {
      list: Post[];
      dtTrigger: Subject<string> = new Subject();
      @ViewChild(DataTableDirective)
      dtElement: DataTableDirective;

      constructor(private service: PostService,private firestore: AngularFirestore,private toastr:ToastrService) { }

      ngOnInit() {
        this.service.getPost().subscribe(actionArray => {
          this.list = actionArray.map(item => {
            return {
              id: item.payload.doc.id,
              ...item.payload.doc.data()
            } as Post;
          })

        });
      }
      onEdit(p: Post){
        this.service.formData = Object.assign({},p);
      }

      onDelete(id: string){
        if(confirm("Are you sure to delete this record")){
            this.firestore.doc("post/"+id).delete();
            this.toastr.warning("Deleted Successfully");
        }
      }

      ngAfterViewInit(): void {this.dtTrigger.next();}

      ngOnDestroy(): void {
        // Do not forget to unsubscribe the event
        this.dtTrigger.unsubscribe();
      }

      rerender(): void {
        this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
           dtInstance.destroy();
           this.dtTrigger.next();     
       });}
    }

forum-admin-list.component.html

    <table datatable class="row-border hover" [dtTrigger]="dtTrigger">
      <thead class="thead-dark">
        <tr>
          <th>Post Number</th>
          <th>Title</th>
          <th>Description</th>
          <th>Date of Publish</th>
          <th>&nbsp;</th>
          <th>&nbsp;</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let post of list">
          <td>{{post.pNo}}</td>
          <td>{{post.title}}</td>
          <td>{{post.description}}</td>
          <td>{{post.date}}</td>
          <td><a class="btn text-danger" (click)="onDelete(post.id)"><i class="fa fa-trash"></i></a></td>
          <td><a class="btn text-primary" (click)="onEdit(post)"><i class="fa fa-edit"></i></a></td>
        </tr>
      </tbody>
    </table>

post.service.ts

    import { Injectable } from '@angular/core';
    import { Post } from './post.model';
    import { AngularFirestore } from '@angular/fire/firestore';
    @Injectable({
      providedIn: 'root'
    })
    export class PostService {
      formData: Post; 
      constructor(private firestore: AngularFirestore) { }

      getPost(){
        return this.firestore.collection('post').snapshotChanges();
      }
    }

Answer №1

It seems that the new datatable is not being generated properly for your POST request. In order to load your POST data, we need to destroy the old table. Please make the necessary adjustments to your code as shown below.

forum-admin-list.component.ts

import { Component, OnInit ,OnDestroy,AfterViewInit,ViewChild} from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { PostService } from 'src/app/shared/post.service';
import { Post } from 'src/app/shared/post.model';
import { ToastrService } from 'ngx-toastr';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
declare var $: any;

@Component({
  selector: 'app-forum-admin-list',
  templateUrl: './forum-admin-list.component.html',
  styleUrls: ['./forum-admin-list.component.css']
})
export class ForumAdminListComponent implements OnInit,OnDestroy,AfterViewInit {
    list: Post[];
    idIndex: any;

    @ViewChild(DataTableDirective)
    dtElement: DataTableDirective;
    dtTrigger: Subject<any> = new Subject();

  constructor(private service: PostService,private firestore: AngularFirestore,private toastr:ToastrService) {
       this.idIndex = 1; 
  }

  ngOnInit() {
    var id = 'tblAdmin' + this.idIndex;
    var table = $('#' + id).DataTable();
    table.destroy();

    this.service.getPost().subscribe(actionArray => {
      this.list = actionArray.map(item => {
        return {
          id: item.payload.doc.id,
          ...item.payload.doc.data()
        } as Post;
      })
      this.dtTrigger.next();
    });

  }
  onEdit(p: Post){
    this.service.formData = Object.assign({},p);
  }

  onDelete(id: string){
    if(confirm("Are you sure to delete this record")){
        this.firestore.doc("post/"+id).delete();
        this.toastr.warning("Deleted Successfully");
    }
  }

  ngAfterViewInit(): void {this.dtTrigger.next();}

  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();
  }
}

forum-admin-list.component.html

<table id="{{'tblAdmin' + idIndex}}" datatable class="row-border hover" [dtTrigger]="dtTrigger">

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

Guide to integrating Gandi.Net API with Node.js in server.js

I'm a beginner in Node.Js and I'm currently working on creating a Mean Stack application. One of the things I need to do is call a 3rd party API, specifically Gandi.Net, from my Node.js code. My Node.Js and Express Application are being used to ...

Encountering a problem during the installation of Angular 4

I'm encountering issues during the installation of the @angular/cli package. Currently, my node version is v6.11.2 and npm version is 5.3.0. My first attempt to install it using sudo npm install -g @angular/cli resulted in an error message that kept ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

Having difficulty invoking the forEach function on an Array in TypeScript

I'm currently working with a class that contains an array of objects. export interface Filter { sf?: Array<{ key: string, value: string }>; } In my attempt to loop through and print out the value of each object inside the array using the forE ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

Uploading images with Angular, Node.js, and MySQL

Is there a way to upload an image to a MySQL blob field using node.js, and then use Angular to display it as an image? I'm looking for suggestions on how to accomplish this. Any ideas? ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

Nested component in reactive forms not functioning as expected

I've been experimenting with creating nested reactive form components. Specifically, I'm working on a reusable input component for my app within a reactive form. How can I dynamically communicate with nested components in Reactive forms? Despite ...

slider malfunctioning when dir="rtl" is used

Looking to incorporate Arabic language support into an Angular Material site, but encountering issues with the mat slider when applying dir="rtl". The problem arises when dragging the thumb in a reverse direction. I attempted a solution that resulted in a ...

filtering an array based on a specific property will result in the original array remaining

Working on filtering an array of objects based on a certain property using the following code snippet: if (payment == Payment.CREDIT_CARD) { this.currenies.filter((currency: Currency) => currency.isFromEurope === true); console.log(this.currencies) ...

PDFKIT does not begin streaming on an HTTP response until I invoke the doc.end() function

I am currently using pdfkit to dynamically generate PDF files and then returning them in an HTTP response for download. Although I am able to successfully download the file on the browser end, the download dialog does not appear immediately. It seems to wa ...

Accessing Facebook in Ionic 2 Release Candidate 0

I'm interested in adding a Facebook login feature to my Ionic 2 app, but I'm unsure of how to proceed. Most tutorials I've come across demonstrate how to do this with Firebase database, while my project is already using MySql. Can someone gu ...

Is it possible to access your app directly from the browser without requiring any user prompts?

After successfully setting up my app for both android and ios with the necessary app link and universal link, I am now focusing on redirecting users from a specific website to my app. The mobile aspect is all set, but I need to work on the browser/server s ...

Angular 6 - Use *ngIf to apply the readonly attribute to an input when a certain condition is met

In my current project, I am attempting to set a condition on an input field where if a variable equals 'view', then the readonly attribute should be added to the input. Here is the code snippet I am currently using: <input *ngIf="mode == &ap ...

Angular Markdown Styling: A Guide

Currently, I am using Angular and Scully. I would like to add style to the image in a markdown file within Angular, but I am unsure of how to accomplish this task. The image is currently displaying too large. Can anyone provide me with useful advice on how ...

A Typescript object that matches types and eventually returns a string when called upon

In the process of overengineering a type that can match either a string or an object whose valueOf() function, when evaluated recursively, ultimately returns a string. type Stringable = string | StringableObject; interface StringableObject { valueOf() ...

Personalized Carousel using Ng-Bootstrap, showcasing image and description data fields

I have been working on customizing an Angular Bootstrap Carousel and have managed to successfully change the layout. I now have two columns - with the image on the right and text along with custom arrows on the left. My goal is twofold: First, I am lookin ...