Angular 7 - Reload datatables after deleting an item from the table

Asked

Viewed 874 times

0

The datatable presents an error after I delete an item from the table, the message includes a site that eh this: Cannot reinitialise Datatable

I thought of some way to "go back and forth" the page to refresh the table, but I did not succeed. The test that did not work was with the "this.router.navigate(['modules']);"

I came to the conclusion that I should insert some command in the function "getList()" or "delete()".

Modules.component.ts

import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { Router } from "@angular/router";
import { Subject } from 'rxjs';

import { Modulos } from '../../interface/modulos';
import { ModulosService } from '../../services/modulos.service';

@Component({
  selector: 'app-modulo',
  templateUrl: './modulos.component.html',
  styleUrls: ['./modulos.component.css']
})
export class ModulosComponent implements OnDestroy, OnInit {

  public modulos: Modulos[];
  deleteModalRef: BsModalRef;
  deleteId: number;
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  @ViewChild('deleteModal') deleteModal;

  constructor(private modulosService: ModulosService,
              private bsModalService: BsModalService,
              private router: Router) { }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10
    };

    this.getList();
  }

  getList() {
    this.modulosService.getList().subscribe(
      (modulos: Modulos[]) => {this.modulos = modulos; this.dtTrigger.next();}, //this.dtTrigger.next();
      (error) => {console.log(error); }
    );
  }
  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();

  }
  onDelete(id: number) {
    this.deleteId = id;
    this.deleteModalRef = this.bsModalService.show(this.deleteModal, {class: 'modal-sm'});
  }
  onConfirmDelete() {
    this.delete(this.deleteId);
    this.deleteModalRef.hide();
  }
  onDeclineDelete() {
    this.deleteModalRef.hide();
  }
  private delete(id: number) {
    this.modulosService.delete(id).subscribe(
      (response) => {console.log(response); this.router.navigate(['modulos']); },
      (error) => {console.log(error); }
    );
  }
}

Modules.component.html

<h4 class="m-3"> Modulos</h4>
<nav class="nav">
    <button class="btn btn-success m-3" [routerLink]="['new']">Criar Módulo</button>
</nav>
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-light mx-3 text-secondary">
  <thead class="thead-light">
    <tr>
      <th>ID</th>
      <th>Nome</th>
      <th>Descrição</th>
      <th>Sistema</th>
      <th>Setor</th>
      <th>Modulo Pai</th>
      <th>Ações</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let m of modulos">
      <th>{{ m.id_modulo }}</th>
      <th>{{ m.nome_modulo }}</th>
      <th>{{ m.descricao }}</th>
      <th>{{ m.nome_sistema }}</th>
      <th>{{ m.nome_setor }}</th>
      <th>{{ m.nome_modulo_pai }}</th>
      <th><button class="btn btn-sm btn-info mr-2" [routerLink]="[m.id_modulo, 'edit']">Editar</button>
        <button class="btn btn-sm btn-danger mr-2" (click)="onDelete(m.id_modulo)">Deletar</button>
        <button class="btn btn-sm btn-secondary" [routerLink]="[m.id_modulo, 'add']">Criar Formulário</button>
      </th>
    </tr>
  </tbody>
</table>

<ng-template #deleteModal>
  <div class="modal-body text-center">
    <p>Tem certeza que quer deletar?</p>
    <button type="button" class="btn btn-default" (click)="onConfirmDelete()">Sim</button>
    <button type="button" class="btn btn-primary" (click)="onDeclineDelete()">Não</button>
  </div>
</ng-template>

Modulos-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ModulosComponent } from './modulos.component';
import { ModulosFormComponent } from './modulos-form/modulos-form.component';
import { ModulosShortcutComponent } from './modulos-shortcut/modulos-shortcut.component';

const routes: Routes = [
  { path: '', component: ModulosComponent},
  { path: 'new', component: ModulosFormComponent},
  { path: ':id/edit', component: ModulosFormComponent},
  { path: ':id/add', component: ModulosShortcutComponent},
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ModulosRoutingModule { }

  • I searched, edited, tested and failed to update the datatables. If anyone knows, please leave a comment or answer to help resolve this issue.

1 answer

1


Hello, you can try updating the table using setTimeout(), use a *ngIf="show" (in the table) and a Boolean variable, where it will cause the table to appear and disappear from the DOM.

For example:

att() {
thiS.getList() // para atualizar o dados do array
  this.show = false // tirar tabela do DOM
    setTimeout(() => {
      this.show = true // retorna com tabela para o DOM e os dados atualizados do 
                          this.getList()
    }, 50);
}
  • 1

    It worked, thank you very much for your help!

  • 1

    Thanks, buddy. I was having the same problem these days, only managed to solve this way. I could mark the answer as useful?

  • 1

    Give a Up in the post to help tbm! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.