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:

https://i.sstatic.net/P9F74.png

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

A step-by-step guide on connecting an event listener to the search input of Mapbox GL Geocoder in a Vue application

I've encountered a challenge trying to add an event listener to the Mapbox GL Geocoder search input within a Vue application. It appears to be a straightforward task, but I'm facing difficulties. My objective is to implement a functionality simi ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

What is the method for asynchronously loading a javascript file that includes an ajax call?

Within my JavaScript file named JScript.js, there is a function that includes an AJAX call to a dot-net page. alert('jscript.js called'); function AddTag() { var htag = document.getElementById("hdntag").value.split('|'); var texttag = ...

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Load data asynchronously using a promise in select2

Is there a way to load options for select2 asynchronously without using ajax requests? I want to retrieve values from a promise object instead. Currently, my code loads data in the query function, but this means that it queries the data with every keystrok ...

Steps to have the initial link redirect to a designated webpage

I am working with tables that have links defined in the HTML. I want to modify the behavior so that the first link opens a different URL, for example: john.com. Is it possible to achieve this? Specifically, I want the link associated with the first name ( ...

After the update to the page, the DOM retains the previous element

I'm currently developing a Chrome Extension (no prior knowledge needed for this inquiry...) and I have encountered an issue. Whenever I navigate to a page with a specific domain, a script is executed. This script simply retrieves the value of the attr ...

Pop-up alert for text sections that are longer than a specific character limit

As I work on a website featuring dynamically generated blog posts of varying lengths, I'm looking to restrict the height of each post to 250px. Should a post exceed this limit, I want to truncate it and include a "read more" link that opens a modal ov ...

Having difficulty with loading JSON data into jqGrid

Explaining my jqGrid definition: . . . datatype: 'json', //Setting the data type to JSON url:'<%=request.getContextPath()%>/servlet/AjaxManager?mode=9999&beginindex=0&totallimit=10&colname=policyname&sorttype=asc&apos ...

Is it possible to obtain the impending exception handling protocol in advance?

In upcoming scenarios, unhandled promise rejections will lead to the termination of the Node.js process using a non-zero exit code. Despite encountering issues, my pipeline erroneously passed and deployed a faulty version that crashes upon launch. If Node ...

Guide on Reacting to an Occurrence in Angular

I have a scenario where an event is triggered every 10 seconds. After subscribing to the event on the receiving end, I need to figure out how to send data back to the class responsible for emitting the event. constructor(@Inject(ABC.XYZ) private events: ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

Replacing a div with another div can be achieved in a single swap

My goal is to swap one div with another div upon clicking using the provided code. It functions properly for a single instance. However, the issue arises when the class appears multiple times, causing all instances to change due to sharing the same class n ...

What steps do I need to take to link my form with Ajax and successfully submit it?

Here is my HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Create a Recipe ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

Error encountered during Angular ng build -prod: The provided parameters do not align with any applicable call target signatures

Every time I try running ng build --target=production, an error pops up like this: ERROR in C:/Repo/NewCo/src/$$_gendir/app/fu/bar/fubar.component.ngfactory.ts (4011,35): Supplied parameters do not match any signature of call target. This error m ...

What is the process for performing interpolation in Angular version 8?

In my Angular project, I have 2 components working together. Component A sends an id using the following code snippet: <a [routerLink]="['/numbersbyareacode', element.id]"> {{element.title}} </a> Upon navigating to Component B, ...

Obtaining the ViewRef of the current component in Angular 4

How can I obtain the ViewRef for my current component? I am attempting to retrieve the ViewRef from a service. Below is the code: component.service.ts import { Injectable, ViewRef } from '@angular/core'; @Injectable() export class CheckboxSe ...