1

I'm new to Angular, I have a datatable that includes dynamic data, I'm trying to refresh the table whenever I add any data however for some reason the data is not being put unless I refresh the page myself, I read the documentation however, the only option that I found is renderer but it's not giving me the result I'm looking for, also I've searched all over the internet and all of what I found was a work around that didn't even work in my case, I would appreciate if you can help me refresh the table automatically.

employeeposition.component.ts

ngOnInit(): void {
  // this approach works great when refreshing dropdown menu, but not in datatables
  this.restService.refreshNeeded$.subscribe((res: any) => {
    this.getAllPositions();

  this.dtOptions = {
    destroy: true,
    responsive: true,
    pagingType: 'full_numbers',
    pageLength: 5
};

})

getAllPositions(){
  return this.restService.GetAllPositions().subscribe((res: any) => {
    this.positions = res.data.positions;
    this.dtTrigger.next();
    this.loading = false;
  })
}

2 Answers 2

1

You need to destroy datatable instance before triggering it again.

Try like this:

import { DataTableDirective } from 'angular-datatables';

dtElement: DataTableDirective;

isDtInitialized:boolean = false

  getAllPositions() {
    this.restService.GetAllPositions().subscribe((res: any) => {
      this.positions = res.data.positions;
      this.loading = false;

      if (this.isDtInitialized) {
        this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
          dtInstance.destroy();
          this.dtTrigger.next();
        });
      } else {
        this.isDtInitialized = true
        this.dtTrigger.next();
      }
    })
  }
Sign up to request clarification or add additional context in comments.

3 Comments

unfortunately I had an error Cannot set property 'data' of null when I added this block of code
Works like a charm, Thank you so much you saved the day
Where is the dtTrigger instance?
0

It is expected behaviour as your angular application does not know the database has been modified. One of the ways to update the view is to make the GET call again whenever anything is modified in the DB.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.