Angular 6 DataTables - Table Items Appear/Disappear Upon Sort or Search

angular datatable
angular datatable search
angular datatables buttons
angular-datatables bootstrap
angular-datatables rerender
angular-datatables dtoptions
angular 2 datatables
angular 5 datatable

I am using Angular-DataTables 6.0 (found here https://l-lin.github.io/angular-datatables/#/welcome) and I have been running into a reoccurring problem. When a table item is added or deleted, the record either vanishes or reappears upon sorting or searching. Is this possibly because the adding/deleting is occurring from outside the dataTable?

I've tried adding the ' datatable="ng" ' fix many others suggested but that didn't change anything. I also attempted to add a re-render function, but in that case I ran into 'object unsubscribed' errors that I couldn't resolve. For reference, some similar problems can be found here: Similar examples include: (angular : lost data after sort datatable) (Sorting of numbers within brackets in angular datatables) (https://github.com/l-lin/angular-datatables/issues/852)

Here is my code:

HTML:
  <table datatable="ng" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-hover" id="t1">
                <thead>
                        <tr>
                                <th>
                                    <button id="b5">Asset ID</button>
                                </th>
                                <th>
                                    <button id="b5">Employee ID</button>
                                </th>
                                <th>
                                    <button id="b5">Asset Type</button>
                                </th>
                                <th>View</th>
                                <th>Delete</th>
                              </tr>
                              </thead>
        <tbody>
        <tr *ngFor="let a of assets; let i = index"> 
          <td>{{ a.assetID }}</td>
          <td>{{ a.currentUser }}</td>
          <td>{{ a.assetType }}</td>
          <td><button id="button1" (click)="viewAsset(a)"><i class="fas fa-search"></i></button></td>
          <td><button id="b2" class="btn" (click)="scrapAsset(a)" (mouseenter)="buttonHover(i)" (mouseleave)="buttonHoverLeave(i)"><i class="{{buttonIconArray[i].text}}"></i></button></td>
        </tr>
        </tbody>
        </table>
-elsewhere in the code-
         <button class="btn" id="b1" (click)="addAsset()">Add New Asset</button>&nbsp;

TS

   dtOptions: DataTables.Settings = {};
   dtTrigger = new Subject();

 addAsset()
 {
this.confirmChanges = false;
//Create a new asset:
let a: Asset = {
  assetID: this.assetID,
  currentUser: this.currentUser,
  assetType: this.dropdownMessage,

}
//send a notification to the user that owns the new asset
  let notify: Notice = {
  emplyID: a.currentUser,
  notificationSource: "Asset",
  details: "A new " + this.dropdownMessage + " was added to your assets.",
  timeStamp: new Date()
}

//Add the asset to the server
this.AssetsService.addAsset(a)
      .subscribe(asset => { this.assets.unshift(asset);
                            //All of the inputs need to be emptied
                            this.clearFields(); 
                          })
}

scrapAsset(a: Asset)
{
console.log("The ID is " , a.assetID)
//this.AssetsService.deleteAsset(this.currentAsset).subscribe()
this.confirmChanges = false;



//This deletes the asset from the back-end.
this.AssetsService.deleteAsset(a).subscribe(() => { 
  console.log('test')
  this.assets = this.assets.filter(t => t !== a);
  this.NotificationsService.addNotice(notify).subscribe();
  this.clearFields(); });
  }

dtActivate()
 {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 7,
order: (this.assets.assetType),
orderClasses: false,
};
this.AssetsService.getAssetsIT().subscribe((assetsImported) => {
this.assets = assetsImported;
this.parseData();
  // Calling the DT trigger to manually render the table
  this.dtTrigger.next();
});
}

This is only a partial section of the code, so if you need to see more, just ask. Thank you for any help you might provide!

I've had the same problem for a long time. After a lot of stack overflow and documentation, I found a solution that fixed my problem. Maybe it helps you too.

Allow datatable to be destroyed
ngOnInit() {
  this.dtOptions = {
    destroy: true,
    ...
  };
  ...
}
The method that received new items (called after edit, insert, add...).
onReceived(items){
    let isFirst = this.items.length === 0;
    this.items = <itemsModel[]>items;

    if (isFirst)
      this.dtTrigger.next();
    else
      this.rerender();
}
The rerender as in documentation
rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.destroy();
        this.dtTrigger.next();
    });
}

https://l-lin.github.io/angular-datatables/#/advanced/rerender

I hope that this might help you.

"No data available in table" still appears after rows are , Angular 6 DataTables - Table Items Appear/Disappear Upon Sort or Search - html. In this article I am going to explain how to use and integrate the jQuery datatable with AngularJS. DataTables is a prebuild functionality and a plug-in for the jQuery JavaScript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

this will work, but i am still looking for better solutions setTimeout(function () {$(function () {$('#ng').DataTable();});}, 10);

Angular Way, However the "No data available in table" still appears after the table data is loaded and after I tried to sort a column, all the data disappeared. I am using Angular JS for front-end, and specifically ng-repeat to generate the rows. 842 Editor · 11 FixedColumns · 6 FixedHeader · 6 ColReorder · 12 KeyTable  a complete example of how to implement an Angular Material Data Table with server-side pagination, sorting and filtering using a custom CDK Data Source. a running example available on Github, which includes a small backend Express server that serves the paginated data. Table Of Contents. In this post, we will cover the following topics:

You can remove the ng, Following code fixed my problem

<div class="container-fluid">
    <div class="page-title">
        <h4>Milk Types</h4>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-block">  

                    <a href="" class="btn btn-success" href=''  [routerLink]="['/milk/create-milk']">
                        <i class="ti-zip pdd-right-5"></i>
                        <span>Add New Milk</span>
                    </a>

                    <div class="table-overflow">
                        <table class="table table-lg table-hover" datatable [dtTrigger]="dtTrigger" [dtOptions]="dtOptions">
                            <thead>
                                <tr>                                    
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Status</th>
                                    <th>Price</th>
                                    <th></th>   
                                </tr>
                            </thead>
                            <tbody>
                                <tr *ngFor="let drink of data">                                    
                                    <td>
                                        <div class="mrg-top-15">
                                            <b class="text-dark font-size-16">{{ drink.id }}</b>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="mrg-top-15">
                                            <span class="text-info pdd-left-20"><b>{{ drink.name }}</b></span>
                                        </div>
                                    </td>  
                                    <td>
                                            <div class="col-md-5">
                                                    <div class="toggle-checkbox toggle-success checkbox-inline">
                                                    <input type="checkbox" name="isEnabled" id="toggle4" [checked]="drink.isEnabled">
                                                    <label for="toggle4"></label>
                                                    </div>
                                            </div>
                                    </td>
                                    <td>
                                        <div class="mrg-top-15">
                                            <span class="text-info"><b>KD {{ drink.price }}</b></span>
                                        </div>
                                    </td>  
                                    <td>
                                        <div class="mrg-top-10 text-center">
                                            <a href="" class="btn btn-warning">
                                                <i class="ti-comment pdd-right-5"></i>
                                                <span>Edit</span>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table> 
                    </div>
                </div>
            </div>
        </div>
    </div>  
</div>    



import { Component, OnInit, Input, OnDestroy , ViewEncapsulation } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { pipe, Subscription } from 'rxjs';
import { MilksItem, MilksDataSource } from './milks-datasource';
import { Subject } from 'rxjs';

@Component ({
    templateUrl: 'milk.html'
})

export class MilkComponent implements OnInit {

    dtOptions: DataTables.Settings = {};
    subscription: Subscription;
    data: MilksItem[] = [];
    dtTrigger: Subject<MilksItem> = new Subject();

    constructor(private db: AngularFireDatabase) 
    {

    }

    ngOnInit() {

        this.dtOptions = {
            pagingType: 'full_numbers'
        };

        this.subscription = this.db.list<MilksItem>('milkTypes').valueChanges().subscribe(d=>{
          console.log('data streaming');
          this.data = d;
          this.dtTrigger.next();
        });    
    }

    ngOnDestroy(): void {
        this.subscription.unsubscribe();
        this.dtTrigger.unsubscribe();
    }
}

angular-datatables Buttons disappearing on data change · Issue , So, I have integrated angular-datatables into a project which uses UI Way - Data Disappears After Sorting and/or Custom DT API .search() call #413 The problem is, when I click on the column header to sort, or try to search, or click on an table-striped table-bordered table-hover dataTables-example">  Angular 6 DataTables - Table Items Appear/Disappear Upon Sort or Search the record either vanishes or reappears upon sorting or searching. (angular : lost

How to Use a JavaScript DataTable in an Angular Application, Hello, I'm using angular-datatables v0.5.1, along with the Buttons plugin, of the table - 'Copy', 'Print', 'CSV' buttons from the plugin just disappears. ottoyiu opened this issue on Nov 6, 2015 · 27 comments <tr> <td>test</td> </tr> <tr ng-​repeat="row in rows"> <td ng-repeat="col in Will look into a work around if I can​. Show / hide columns dynamically This example shows how you can make use of the column().visible() API method to dynamically show and hide columns in a table. Also included here is scrolling, just to show it enabled with this API method, although it's not required for the API function to work.

Table, So why don't we use one of the seasoned JavaScript data tables? When you're reading this article, things have probably improved. The demos look nice, and I guess you can pass almost every option of the JavaScript vaadin-grid, angular2-iron-data-table (which is built on a Polymer datatable) and  Showing the data set in the table in angular 4 is quite easy. Several free plugins can be used to display data in tables like angular2-datatable that will discuss in this article. angular2-datatable is a table of components that have been equipped with pagination and sorting data features. Also, this plugin has support with the bootstrap framework so that it can be applied to the mobile display.

Search Sort and Pagination in ng-repeat, The table provides a foundation upon which other features, such as sorting and see the documentation for MatTable which builds on top of the CDK data-table. depending on what type of rows you want rendered (e.g. if you do not need a set via binding to support dynamically changing the columns shown at run-time.

Comments
  • Did you find the solution?
  • I have not. The solution below didn't help my original problem.
  • i fixed it, let me know if you want to find the solution
  • Absolutely, go ahead and post the solution.
  • Alright, I just tested this code out, and it seemed to partially work. The DataTable did update in real time, however, I got an error that appears as a popup: "DataTables warning: table id=t1 - Cannot reinitialise DataTable. For more information about this error, please see datatables.net/tn/3".
  • sorry.. there's one more thing, I will try to update the answer, you have to allow the destroy.
  • I had one bug with this code once because my list can change from empty to not empty at one particular case (so sometimes rerender was not called). So the condition for the first time has to be evaluated in your case.
  • dear @Danchat could you test the modification I did?
  • are you calling rerender everytime your datatable is changed (adding, removing, ...) and did you called dtTrigger.next(); the first time your databales was filled ?
  • Where in the code are you putting this? I tried placing this after adding or removing an entry in the datatable but the problem still persists.
  • @Danchat set it inside ngOnInit() { setTimeout(function () {$(function () {$('#ng').DataTable();});}, 50); }, inside your component, so when page is load it will render your datatable
  • The Datatable itself is rendering fine, but my problem is that the table cannot be updated (add or delete records) without refreshing the webpage. Putting this code in ngOnInit didn't change that.
  • I did my best to replicate your code and I wasn't able to get it to work. Since I'm using services and MongoDB as the back-end and I tried using 'subscription' like you did, perhaps there was some sort of incompatibility there. Is there any way you could put this code up on a place like Plunker and then I could see how the code works running live?