A guide on leveraging the modal window function within Angular

I have a simple list of files with a "Delete" button. I have added a modal window for confirmation, but I am unsure how to connect the Delete function from the main component to the modal window. The modal window is implemented using the @angular/material library. My objective is to delete a file by clicking the button with the class `accept()` in the modal window.

export class FileService {

constructor(private http: HttpClient, @Inject('BASE_URL') 
baseUrl: string, public dialog: MatDialog ) {}

public openDeleteModal(name: any, id: any) {
this.dialog.open(DeleteDialog, { data: { name , id} }); 
}

public fileDelete(id) {
return this.http.delete(this.Url + '/delete' + id).subscribe(
  data => {
    console.log("DELETE Request is successful ", data);
  },
  error => {
    console.log("Error", error);
  })
 }
 }

@Component({
selector: 'list-files-deletedialog',
templateUrl: './list-files-deletedialog.component.html',
  })
export class DeleteDialog {
constructor(public dialogRef: MatDialogRef<DeleteDialog>,
@Inject(MAT_DIALOG_DATA) public data: any) { }

 public accept(): void {

  // Here I need to integrate the fileDelete function
 }

 close(): void {
  this.dialogRef.close();
 }
}

Answer №1

You have the option to utilize the callback function

export class FileService {

constructor(private http: HttpClient, @Inject('BASE_URL') 
baseUrl: string, public dialog: MatDialog ) {}

public openDeleteModal(name: any, id: any, cb?: any) {
   let deleteModelRef: MatDialogRef<DeleteDialog>;
   this.dialog.open(DeleteDialog, { data: { name , id} }); 

   deleteModelRef.afterClosed().subscribe(result => {
        if (cb) {
            cb();
        }
   });
}

public fileDelete(id) {
  return this.http.delete(this.Url + '/delete' + id).subscribe(
    data => {
      console.log("DELETE Request is successful ", data);
    },
    error => {
      console.log("Error", error);
    })
   }
}

as well as DeleteDialogue.component

@Component({
selector: 'list-files-deletedialog',
templateUrl: './list-files-deletedialog.component.html',
  })
export class DeleteDialog {
constructor(public dialogRef: MatDialogRef<DeleteDialog>,
@Inject(MAT_DIALOG_DATA) public data: any, private fileService: FileService) { }

 public accept(): void {

  this.fileservice.openDeleteModal('name',id, cb => {
     // you can invoke the delete service here
     this.fileservice.fileDelete(id);
  });
 }

 close(): void {
  this.dialogRef.close();
 }
}

Answer №2

Don't forget to include this in your modal template:

...

<mat-dialog-actions align="end">
  <button mat-button mat-dialog-close>Cancel</button>
  <button mat-button [mat-dialog-close]="data" cdkFocusInitial>DELETE</button>

...

Make sure to subscribe for the data

 openDialog(data) {
        const dialogRef = this.dialog.open(DialogContentExampleDialog);

        dialogRef.afterClosed().subscribe(data=> {
          return this.http.delete(this.Url + '/delete' + id).subscribe(
          data => {
          console.log("DELETE Request is successful ", data);
  },
  error => {
    console.log("Error", error);
  })

}); }

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 to incorporate the router into the observable within the guard?

Is there a way to inject a router into my guard when I have an Observable method returned? I want to implement routing with a redirect to the login page if a certain condition is met: If the result of the isAccessToLobby method is false, then redirect to t ...

What is the best method for incorporating a private key into a service without exposing it in the front-end code?

I am currently working on incorporating a private API key into a service by fetching it from a secure endpoint on the server. However, I am unsure of the correct approach to integrate this key into the required service. Confession time - I'm feeling ...

Ways to manage a two-click event on a covalent table

After facing challenges with the angular/material datatable integration, I decided to switch to Teradata covalent datatable. However, I am currently struggling with implementing a double click event on a specific row of the data table. Can someone guide ...

Guidelines for declaring types in variable definitions in Typescript

In Typescript, you have multiple options to define a boolean variable such as: let a = true; let b: boolean = true; Given that true is already a boolean value, is it still typical to explicitly declare the variable type (like shown for b)? If yes, does ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Suggestions for autofilling in Angular 8 on the password field

Despite multiple discussions on stackoverflow, a solution to disabling browser AUTO-FILL suggestions on fields still eludes me. Does anyone know of a reliable method to prevent these pop-ups from appearing? <mat-form-field> <input ...

Having difficulty incorporating TypeScript into Vue

A little while ago, I set up a vue project using vue init webpack . and everything was running smoothly. Recently, I decided to incorporate typescript and ts-loader. I created a file in the src directory with the following content: declare module '* ...

Navigating Angular's Credit Card Input Functionality

I am looking to limit the input capacity to 16 numbers and add a space between each set of 4 numbers. After conducting an extensive search for a credit card input that allows users to enter 16 digits with a " - " or space in between, all results were for ...

Issue with incorrect inference of TextField `helperText` when using Formik with Material-UI

Upgrading to react-scripts 5 has caused an issue with the helperText on the TextField component. My TypeScript knowledge is not strong, so I'm having trouble fixing it. Here's more information about the problem: The error message: TS2322: Type & ...

Converting input tag to a method in component with uppercase transformation

Currently, this code resides within the <input tag I am looking to convert this code into a method in my component. Any ideas on how to do this? oninput="let p=this.selectionStart; this.value=this.value.toUpperCase(); this.setSelectionRange(p,p) ...

How to dynamically customize styling on md-tab in Angular2-material?

Styling material design components can be challenging, especially when trying to dynamically set styles on an md-tab based on its active or archived state. I'm looking to make the tab header text italic and change its color to indicate whether it is a ...

When attempting to execute my script, I encountered an error message stating that "TypeError: puppeteer.use(...) is not

Here is the current code that I've been working on. After switching it to a new folder, I encountered an error that wasn't present before. I made sure to reinstall all the necessary modules in the package.json file, but the issue persists. Is the ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

retrieve data from URL parameters (navigation backward)

When navigating from the main page to the transaction page and then to the details page, I have implemented a go back feature on the details page. Using the state, I pass data when navigating back so that I can access it again from the transaction page. H ...

Utilize Knex to retrieve data from the req.query

express and knex have been giving me some trouble; I am struggling to get this endpoint working using req.querys (response from express), even though it worked fine when I used req.params. Express: app.get(`/actor`, async (req: Request, res: Response) =&g ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Error TS2307: Module 'passport' is nowhere to be found

Recently, I ventured into a new project using the TypeScript Basic Node.js Express 4 Application template in VS 2017. To enhance my project, I utilized npm to add passport. The addition of passport is reflected under the npm node in Solution Explorer, wit ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...