What is the method to utilize the Escape Key in Angular to dismiss a mat-dialog?

I am currently utilizing angular version 15.0 and I am interested in how to close a mat-dialog using two different methods. The first method involves clicking on one of the two buttons (submit / cancel) that are specified in the actions section of the dialog. The second method is by pressing the Escape key to cancel the operation. Essentially, both the cancel button and the Escape key perform the same action. The snippet used to open the dialog can be found below:

const myDialog = this.operationDialog.open(DialogComponent,
      {
        disableClose: true,          
      });
myDialog.afterClosed().subscribe((result) => {
      if (result !== 'cancel')
        // do somethings
        else
        // operation is canceled
    );

The mat-dialog snippet is as follows:

<mat-dialog-content class="mat-typography">
  ....
</mat-dialog-content>
<mat-dialog-actions>
  <button (click)="submit()">submit</button>
  <button (click)="cancel()">cancel</button>
</mat-dialog-actions>

Furthermore, the typescript snippet for handling submission and cancellation functions is shown below:

submit(){  
    this.dialogRef.close(myData);
  }
  
cancel(){   
    this.dialogRef.close('cancel');
 }

My question is whether it is feasible to close the dialog by hitting the Escape key to achieve the same outcome as clicking the cancel button? I appreciate your response.

Answer №1

It is possible to create a functionality that triggers a response when the Esc key is pressed. By listening to keystrokes, you can set up an event listener specifically for the Escape key.

The code snippet below should be inserted into your Dialog TS file:

private escapeSub$ = new Subject<void>();

ngOnInit(): void {
    this.setupEscapeListener();
}

setupEscapeListener() {
    fromEvent(document, 'keydown').pipe(
        // Only respond to 'Escape' key press events
        filter((event: KeyboardEvent) => event.code === 'Escape'),
        takeUntil(this.escapeSub$)
    )
    .subscribe(() => {
        this.handleCancel();
    });
}

handleCancel(){   
    this.dialogRef.close('cancel');
}

ngOnDestroy(): void {
    this.escapeSub$.next();
}

Answer №2

If you want to implement a custom cancellation logic, you can do so by subscribing to either the beforeClosed or afterClosed Observable. In order for the Escape key to trigger this logic, you must remove the disableClose: true setting.

constructor(...) {
  this.dialogRef.afterClosed().subscribe(() => {
    console.log('The escape key was pressed or the close method was called');
  });
}

cancel() {
  this.dialogRef.close('cancelled');
}

For more information, visit: https://material.angular.io/components/dialog/api#MatDialogRef

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

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

Angular 2 components sharing a common route

Two modules share the same path but have different templates (main and auth). The modules should be loaded based on whether the user is authenticated or not. Unfortunately, this functionality is not currently working as intended. Below are the relevant co ...

Issue with deprecated TypeORM connection and isConnected functions

import { Module } from '@nestjs/common'; import { Connection } from '../../node_modules/typeorm/connection/Connection'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forRoot()], exports ...

Tips for getting Nativescript listview to function properly

I am currently developing an app using nativescript and angular 2. I am facing some issues while trying to implement the nativescript listview component. Whenever I run the app, all I see is " [object object] ". Below is my view code : <grid-layout c ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

HTTP request returns a status code of 200 without any accompanying response data

Attempting to send an http request upon a page refresh in my Angular frontend to a nodejs backend, expecting to receive a token as a response. However, sometimes the request gets cancelled and even when it is successful (status code 200), the token is not ...

Is it possible to import node_modules from a specific directory mentioned in the "main" section of the package.json file?

Is it feasible to import from a source other than what is defined by the "main" setting? In my node_modules-installed library, the main file is located at lib/index.js With es2015 imports (source generated from ts compiled js), I can use the following ...

Modifying the value upon saving in Adonis JS model

Using Adonis js I am facing an issue when trying to convert an ISO string to Datetime while saving data (the opposite of serializing DateTime fields to ISO string). I cannot find a way to do this in the model, like I would with a mutator in Laravel. Whene ...

Semantic HTML in Angular

Having a React background, I'm used to custom components rendering as expected without any extra wrapper tags. However, in the case of Angular, I've noticed that my custom component my-custom-component adds an additional tag around the content. & ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

Changing Angular code to vanilla JavaScript

Here is an example code snippet for a plugin used in an Ionic/Capacitor/Angular project: import { ForegroundService } from '@awesome-cordova-plugins/foreground-service/ngx'; constructor(public foregroundService: ForegroundService) { } ... sta ...

Angular paginator encountered an issue while attempting to parse the template

I'm updating my data list to include pagination, and everything seems fine with retrieving data and sorting. However, when I add the paginator tag to my template, Angular shows me an error: ERROR in Errors parsing template: Unexpected closing tag " ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

What should I do when dealing with multiple submit buttons in NextJS?

How can I differentiate between two submit buttons in a form component created in Next.js? I'm struggling to determine which button was pressed and need help resolving this issue. import React from "react"; const LoginPage = () => { as ...

Guide on transferring information from a node server connected to Google Sheets to Angular 9

Encountered an issue when trying to pass data from a Node server to the front-end using Angular 9. The server side was built with Node and data was fetched from the Google Sheet API. Despite searching extensively on Google, I couldn't find a solution ...

Animating with Angular 2

As I delve into this informative resource, my goal is to incorporate some animations into my applications, but I find myself grappling with understanding how the animations are triggered. HTML Component <div class="navbar navbar-default navbar-fixed-t ...

Add a React component to the information window of Google Maps

I have successfully integrated multiple markers on a Google Map. Now, I am looking to add specific content for each marker. While coding everything in strings works fine, I encountered an issue when trying to load React elements inside those strings. For ...

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...