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

Simplifying imports in Angular, the easy way: A guide to stream

We recently made a change to our Angular project by moving the npm-library @ng-plus/modal to live as a project library under the project/ngplus-modal folder. One issue we encountered is with the imports within the project. Even though we previously def ...

Enhancing Angular2 authentication with Auth0 for enabling Cross-Origin Resource Sharing

I have been working on implementing user authentication through Auth0. I followed the instructions provided on their website, but I am encountering authentication issues. Whenever I try to authenticate, an error message appears in the console stating that ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

Converting retrieved data into table cells through mapping

I'm facing an issue where I need to display specific addresses for each individual in a table row. For simplicity, let's focus on showing the city specifically as described in this code snippet: https://i.stack.imgur.com/bJmsD.png Currently, whe ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

Can a Vue application be made type-safe without the need for transpilation?

Is it possible for Vue to be type-safe when used without transpilation (without a build step) as well? Can TypeScript or Flow be used to ensure type safety? ...

Steps to handle Angular's response to an HTTP 401 error

I am using nodejs (express) as a server side and angular 6 as the client. On the server, I have a middleware function that checks for a session. If the session is invalid or does not exist, I want to send a response to the client so it can handle it accord ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

Guide: Building a Dropdown Form in Angular 2

I have a webpage with an HTML form that includes a button positioned above the form. I am interested in adding functionality to the button so that when it is clicked, a duplicate of the existing form will be added directly beneath it. This will allow for m ...

What is the correct way to bind by reference when utilizing a function that returns an object?

I currently have an object in my Component: this.user = Authentication.user; It's working perfectly fine as it copies the reference. So, if Authentication.user changes, this.user in my Component also changes accordingly. However, I am curious to kn ...

What is the best way to dynamically insert content into a PDF using pdfmake?

In my quest to dynamically generate PDFs using pdfmake, I've encountered an issue with creating dynamic rows based on data. To illustrate, here is a simplified version of the code: getDocumentDefinition(img: string, data: DataResponse, user: UserResp ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...

Exploring the process for transitioning between pages within Angular

I am working on an Angular project and I am looking to navigate to the registration page when the registration button is clicked. As a beginner, I attempted to link the registration page but encountered some issues. My goal is for the main page to disappea ...

The issue arises when IonViewDidLoad fails to retrieve data from the service class in Ionic after the apk file has been generated

Creating a form where users can input various information, including their country code selected from dropdowns. Upon submission, the data is displayed successfully when running in a browser. However, after building the apk file, the country codes fail to ...

Steps for altering the primary color in PrimeNG__Changing the primary color

What is the most effective way to modify the default primary color for primeNG (saga-blue theme)? Altering --primary-color does not have the desired effect, as elements in node_modules/..../theme.css are styled using the main color hex rather than '-- ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...