Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';

/**
 * @title Dialog Overview Example with Angular Material
 */
@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html'
})
export class DialogOverviewExample {

  animal: string;
  name: string;

  constructor(public dialog: MdDialog) {}

  openDialog(): void {
    let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.animal = result;
    });
  }

}

@Component({
  selector: 'dialog-overview-example-dialog',
  templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {

  constructor(
    public dialogRef: MdDialogRef<DialogOverviewExampleDialog>,
    @Inject(MD_DIALOG_DATA) public data: any) { }

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

}

Suppose you have the code above and the result displayed in the screenshot below:

Given this image, how can I identify if the user clicked OK or No thanks? I intend to create a separate function for each button click event. I attempted dialogRefAfterClose but it triggers regardless of which button is clicked.

Answer №1

Within your dialog html file named dialog-overview-example-dialog.html, simply include a (click) event for both buttons.

<div mat-dialog-actions>
  <button mat-button (click)="clickOK()" tabindex="2">Ok</button>
  <button mat-button (click)="clickNo()" tabindex="-1">No Thanks</button>
</div>

You can also programmatically close the dialog using the following:

clickNo() {
    console.log('No button was clicked');
    this.dialogRef.close();
}
clickOk() {
    console.log('Ok button was clicked');
    this.dialogRef.close();
}

Answer №2

Greetings! It has come to my attention that you are utilizing the exact example found in angular.material. The option you are inquiring about should be customized based on your specific needs, as demonstrated in the provided example. Check out my personalized example here

Within this context, the onNoClick() and onOkClick() functions carry out the required tasks. Simply add these functions to the component ts file and bind them accordingly in the component html file.

Dialog Component TypeScript File

export class DialogOverviewExampleDialog {

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

  onNoClick(): void {
    alert("You clicked no.")
    this.dialogRef.close();

  }
  onOkClick():void{

    alert("You clicked Ok");
  }
}

Dialog Component HTML File

<h1 mat-dialog-title>Greetings {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite animal?</p>
  <mat-form-field>
    <input matInput tabindex="1" [(ngModel)]="data.animal">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onOkClick()" [mat-dialog-close]="data.animal" tabindex="2">Ok</button>
  <button mat-button (click)="onNoClick()" tabindex="-1">No Thanks</button>
</div>

Answer №3

To achieve this functionality, you only need to implement a single function for multiple buttons rather than creating separate functions.

Here is an example:

<div mat-dialog-actions>
  <button mat-button (click)="handleButtonClick(true)" tabindex="2">Ok</button>
  <button mat-button (click)="handleButtonClick(false)" tabindex="-1">No Thanks</button>
</div>

handleButtonClick(status) {
    if(status) {
        console.log('Ok button clicked');
    } else {
        console.log('No button clicked');    
    }
    this.dialogRef.close();
}

Answer №4

<button  mat-button  (click)="onNoClick()"  [mat-dialog-close]="data.SelectedBtn">No Thank You</button>
  <button  mat-button  (click)="onOkClick()"  [mat-dialog-close]="data.SelectedBtn" cdkFocusInitial>Okay</button>


@Component({
  selector: 'dialog-overview-example-dialog',
 templateUrl: './dialog.html',
})
export class DialogComponent {

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

 onNoClick(): void {
this.data.SelectedBtn = false;
this.dialogRef.close(this.data.SelectedBtn);
}

onOkClick(): void {
  this.data.SelectedBtn = true;
  this.dialogRef.close(this.data.SelectedBtn);
}


}

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

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

What is the most efficient method for exporting Express route functions for promise chaining?

Currently, I am in the process of refactoring an API route to utilize ES6 promises instead of callbacks, so as to avoid callback hell. Upon successful conversion to a promise chain, my intention was to extract the .then() functions into a separate file fo ...

Unable to remove data once it exceeds 10 entries while using AJAX, jQuery, and JavaScript/PHP

I am having an issue where I can insert data into the first 10 rows and delete any of them successfully. However, when I try to insert data starting from the 11th row, I am unable to delete any rows past the 10th. UPDATE: The deletion function does not wo ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

I encountered an issue while attempting to retrieve data using route parameters. It seems that I am unable to access the 'imagepath' property as it is undefined

Is there a way to access data when the page loads, even if it is initially undefined? I keep getting this error message: "ERROR TypeError: Cannot read properties of undefined (reading 'imagepath')". How can I resolve this issue? import { Compone ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Using HTML5 to display the {{data}} extracted from a JSON file right in the center of the text

Can someone help me with a question about working with html and angular5? <span [innerHTML]="'client.acceptance.explanation'| translate"></span> <span><b>{{data}}</b></span> I have text stored in a json file ...

Reactjs error: Invariant Violation - Two different nodes with the matching `data-reactid` of .0.5

I recently encountered a problem while working with Reactjs and the "contentEditable" or "edit" mode of html5. <div contenteditable="true"> <p data-reactid=".0.5">Reactjs</p> </div> Whenever I press Enter or Shift Enter to create ...

What are the steps for creating a new npm package based on an existing one?

I'm a newcomer to the node ecosystem and the npm package system. In my redux/react web app, I currently make use of the photoswipe package alongside react-photoswipe. Recently, I decided to extend the functionality of the photoswipe package by making ...

Adding or subtracting values in Angular framework to manipulate numbers

I am looking to increment a number from 1 to 50. I attempted to use the following code, but unfortunately the function is not working properly. See Demo Here Here is the HTML: <Button text="+" (tap)="plus()"></Button> <Button text="-" (t ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

watcher using RxJS

After recently diving into the Observable and Observer pattern, I came across various resources that describe Observable as a producer and Observer as a consumer. However, as I analyzed the code snippet below, I found myself puzzled by the role of the obse ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...

The function for batch insertion only functions with Postgresql and SQL Server databases

I am a beginner in JavaScript and I am currently working on creating a new restaurant. I have come across a code snippet that inserts a relation into a join-table: await newRestaurant.$relatedQuery('tags', trx).relate(tagIds); Is it not possible ...

Update the CURLOPT_URL parameter to accept user input

As someone new to coding, I have a question about using the CURLOPT_URL function in PHP. How can I input a NIK number and retrieve data from this URL: ? Any help would be appreciated, thank you! php $curl = curl_init(); curl_setopt_array($curl, [ CU ...

What is the best way to make mouse and touch events trigger responses in Angular versions 9 and above?

I've been searching high and low for a library or tried-and-true method to handle common user events reactively, but unfortunately my quest has come up empty. After some digging, I stumbled upon what seemed like a solid solution: https://github.com/t ...

Guide on showcasing all entries in the database within the body section of an HTML table

Looking to showcase data from a table inside the body section of an html page This is the code I've been working on: <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vi ...

"Enhance Your Website with jQuery Mobile's Multi-Page Setup and Panel

I am currently facing the challenge of managing multiple pages within a single document and I would like to utilize jQM 1.3's Panel widget to control navigation between these pages. However, the issue arises from the requirement that Panels must be co ...