Eliminate using a confirmation popup

My attempts to delete an employee with a confirmation dialog are not successful. I have already implemented a splice method in my service code. The delete function was functioning correctly before adding the confirmation feature, but now that I have upgraded my code with confirmation, the delete operation is not working. I suspect there might be an issue in the delete method of my service. Can someone assist me in troubleshooting and fixing my code?

EmployeeDetailsComponent: This component links to or displays the confirm dialog component.

<div class="main-content" *ngIf="selectedEmployee">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header card-header-info">
                        <h4 class="card-title "><b>Employee {{selectedEmployee.id}} Details</b></h4>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered border-primary">
                                <thead class=" text-primary">
                                    <th scope="col">Employee ID</th>
                                    <th scope="col">Last Name</th>
                                    <th scope="col">First Name</th>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            {{selectedEmployee.id}}
                                        </td>
                                        <td>
                                            {{selectedEmployee.lastName}}
                                        </td>
                                        <td>
                                            {{selectedEmployee.firstName}}
                                        </td>
                                    </tr>
                                </tbody>
                            </table>


                            <div class="text-right">
                                <button type="button" (click)="updateEmployee(selectedEmployee.id)"
                                    class="btn btn-default"><b>Update</b></button>
                                    <div class="space">
                                    </div>
                                <button type="button" (click)="openDialog()" 
                                    class="btn btn-danger"><b>Delete</b></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

ConfirmComponent: Displays the confirm dialog.

<div>
<div class="header">
    <h2 mat-dialog-header>Title</h2>
    <button mat-icon-button>
        <mat-icon>close</mat-icon>
    </button>
</div>

<div mat-dialog-content>
    Are you sure you want to delete this?
</div>
<div mat-dialog-sections [align]="'end'">
    <button mat-raised-button [mat-dialog-close]="false">No</button>
    <button mat-raised-button color="primary" [mat-dialog-close]="true" (click)="navigateBack()" (click)="deleteEmployee(selectedEmployee.id)" >Yes</button>
</div>
</div>

DialogService

import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ConfirmComponent } from './confirm/confirm.component';
import { EMPLOYEELIST } from './EmployeeData';
@Injectable({
  providedIn: 'root'
})
export class DialogService {

  constructor(private dialog: MatDialog) {

   }

   confirmDialog(){
    this.dialog.open(ConfirmComponent);
   }
 
   deleteEmployee(id: number) {
    const index = EMPLOYEELIST.findIndex((employee: any) => employee.id === id);
    if (index !== -1) EMPLOYEELIST.splice(index, 1);
  }

}

Answer №1

It is important to note that the delete function cannot be directly called within the dialog component.

To achieve this, you can follow these steps:

In the Employee Details Component:

confirmAndDeleteEmployee( id: number ): void {
  const dialogRef = this.dialog.open(ConfirmComponent);

  dialogRef.afterClosed().subscribe(result => {
    if ( !!result ) {
       this.deleteEmployee( id );
    }
  });
}

As for the Dialog Component:

onConfirmDeleteEmployee(): {
  this.dialog.close(true);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Angular 6: utilizing the input field value in the component

I am having trouble passing the input field value to the component class. The code I have is not working as expected. Take a look below: todoinput.component.html <mat-card> <form> <mat-form-field class="example-full-width"> ...

The list in Ionic 3 search does not appear after clearing the search bar

Can anyone assist me with my search bar issue? I'm able to display words on the list, but once I clear the search bar, nothing shows up. Here is a snippet of my code: In my home.html file: <ion-searchbar (ionInput)="getItems($event)" [showCancelB ...

Selecting ion-tabs causes the margin-top of scroll-content to be destroyed

Check out the Stackblitz Demo I'm encountering a major issue with the Navigation of Tabs. On my main page (without Tabs), there are simple buttons that pass different navparams to pre-select a specific tab. If you take a look at the demo and click t ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

Generic interface function in Typescript

Having some issues with my generic interface function. Seems like I've been staring at it for too long... Can someone please point out what I'm doing wrong? This is my Interface: export interface Compareable<T> { equals(compareable:T) ...

Struggling to locate the module with the imports of { async, TestBed } from '@angular/core/testing' and { IonicModule } from 'ionic-angular'

Unable to locate module: import { async, TestBed } from '@angular/core/testing'; import { IonicModule } from 'ionic-angular'; Working with Ionic 3, attempting to perform Unit testing on my application but encountering issues in the s ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows: My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's ...

Utilizing the ABP framework for implementing pagination in ngx datatable

Is there a way to display pagination footer in ngx datatable within the abp framework for Angular? I am currently using ListService with PagedResultDto. Do I need to implement pagination externally? <ngx-datatable [scrollbarH]="false&quo ...

Adding a value to an array in TypeScript

When trying to add values to an array in my code, I encountered an error stating that "number" is not a valid type for the array. someArray: Array <{ m: number, d: Date}> = []; this.someArray.push(500,new Date(2020,1,15)); ...

The date in a nodejs application appears to be shifted by one day

Despite similar questions being asked before here, the solutions provided did not resolve my issue. Here is the scenario I am dealing with: https://i.sstatic.net/H9rcO.png Upon clicking save, I collect data from certain fields to generate a date using th ...

What is the best approach when one property of a typescript class relies on the values of two others?

Currently, I have a TypeScript class within an Angular application that consists of three properties. The first two properties can be changed independently using [(ngModel)]. However, I am looking for a way to set the third property as the sum of the first ...

Troubleshooting Angular 2 Component: Why is console.log not functioning in Typescript?

I'm fairly new to both Angular2 and typescript. Given that typescript is a superset of javascript, I assumed that functions like console.log would function as expected. Interestingly, console.log works perfectly in .ts files when placed outside a comp ...

A step-by-step guide to integrating a legend on a leaflet map using Angular and the ngx-leaflet plugin

I am attempting to integrate a legend into a map generated using Asymmetrik/ngx-leaflet. The tutorial I followed for creating the map can be found at https://github.com/Asymmetrik/ngx-leaflet. There are two distinct layers on the map, each requiring its ow ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...