angularangular-datatables

Re-render DataTable in Angular 2


In my component I am using datatables to show the data from my backend. I am able to get the data from the backend (using a service), parse it successfully and show the data in the data-table. However, my problem is that when my component is first rendered, the network call has not yet completed and hence the table is populated with "No data available in table". Once the network call completes the table gets populated with the data from the server but the message "No data available in table" is still present.

Here is my network call code -

fetchData(){
    this.networkservice.getAllReceipts()
          .subscribe(

            res => {
              this.itemList = res;
            }, error => alert(error),
            () => this.showData());
  }

I am calling this method inside the ngOnInit(). I have also tried calling this method inside the constructor as well as inside ngAfterViewChecked(), but no success.

My showData() method never gets called.

In the documentation of data-tables they have mentioned something called rerender() which can be used to re-render the table but I cant figure out where I should use it. I have it placed inside my showData() method but it never gets called.

I have also used "setTimeout" to set a timeout of 5 secs but even that doesn't seem to work.

My HTML Code-

<table id="receiptTable" [dtTrigger]="dtTrigger" datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>LastName name</th>
      <th>Action</th>
    </tr>
  </thead>

  <tbody *ngIf="itemList">
      <tr *ngFor="let user of itemList">
        <td>{{user.id}}</td>
        <td>{{user.firstName}}</td>
        <td>{{user.lastName}}</td>
        <td><button (click)="getUser(user.id)">Edit</button></td>
      </tr>
    </tbody>
</table>

Please help.


Solution

  • It would be better if we had more code to look at but you can also have a look here where the following additions are mentioned for the datatables-angular module usage:

    // We use this trigger because fetching the list of persons can be quite long,
    // thus we ensure the data is fetched before rendering
    dtTrigger: Subject = new Subject();
    
    ngOnInit(): void {
        this.http.get('data/data.json')
          .map(this.extractData)
          .subscribe(persons => {
            this.persons = persons;
            // Calling the DT trigger to manually render the table
            this.dtTrigger.next();
          });
      }