2

I would like to refresh the items showed in a mat-table after deleting one item, without accessing again to server. It is working fine if I am deleting the item directly from delete button in a row, but it is not working when using a mat-dialog.

Here is my code doing directly (this is working):

HTML:

<button mat-button (click)="delete(element)"></button>

TS:

    public delete(element) {
    this.myService.delete(element.ID).then(() => {
      const index = this.dataSource.data.findIndex(q => q.ID == element.ID);
      this.dataSource.data.splice(index, 1);
    })
  }

And here my code doing thorough mat-dialog, where it is not refresing the table:

HTML:

<button mat-button (click)="openDialog(element)"></button>

TS:

public openDialog(element) {
    const dialogRef = this.dialog.open(DeleteItemDialogComponent, {
      panelClass: ['backOfficeDialog'],
      data: {itemType: 'Document'}
    });
    dialogRef.afterClosed().subscribe(response => {
      if (response.event == 'Delete') {
        this.delete(element);
      }
    });
  }

  public delete(element) {
    this.myService.delete(element.ID).then(() => {
      const index = this.dataSource.data.findIndex(q => q.ID == element.ID);
      this.dataSource.data.splice(index, 1);
    })
  }

MatDialogItem:

    export class DeleteItemDialogComponent implements OnInit {

  constructor(
    public dialogRef: MatDialogRef<DeleteItemDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) { }

  ngOnInit() {
  }

  public delete() {
    this.dialogRef.close({event: 'Delete'});
  }

  closeDialog() {
    this.dialogRef.close({event: 'Cancel'});
  }
}

Do you know why in the second case it is not refreshing the table, what I am doing wrong, and how to solve it?

Thank you!

1 Answers1

0

Just call ngOnInit(). But if you have subscribers, they must be unsubcribed into ngOnDestroy, then call first ngOnDestroy and then ngOnInit. This will work fine and update data without refresh page.

Winter Squad
  • 169
  • 7