How to make button in mat-dialog work on Enter also?

Viewed 2927

I have a mat-dialog-box where on click event it closes the dialog but I want it to work on Enter press also. Is there any way to do so?

I have tried using a form but didn't work. Below is my solution what I tried to use:

HTML

<form (submit)="doAction()">
   <button type="submit">Add</button>
</form>

TS

doAction() {
  this.dialogRef.close({ event: this.action, data: this.local_data });
}

But the Enter event is not occurring though on click it's submitting the data. Also for normal forms (which is not in a dialog) works on Enter press if I take the above HTML approach.

Can anyone suggest the issue?

2 Answers

In your dialog component add a HostListener, like this (a full but simple component):

A full working example here.

HTML

<p>
my-dialog works!
</p>

<form (submit)="close()">
  <input type="text">
   <button type="submit">Add</button>
</form>

<button mat-button (click)="close()">Close</button>

TS

import { Component, HostListener, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-my-dialog',
  templateUrl: './my-dialog.component.html',
  styleUrls: ['./my-dialog.component.css']
})
export class MyDialogComponent implements OnInit {
  constructor(private dialogRef: MatDialogRef<MyDialogComponent>) { }

  @HostListener('window:keyup.Enter', ['$event'])
  onDialogClick(event: KeyboardEvent): void {
    this.close();
  }
}

ngOnInit() {
}

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

}

Where-ever you want the function to call on click of 'Enter' button, simply add this event along with the (click) event

(keypress.enter)="yourFunction($event)"

This works perfectly.

Actual keyboard event for the button to work is through the click of spacebar.

If your requirement is definitely Enter button, then add

(keypress.enter)="yourFunction($event)" 

otherwise simply add

(keypress)="yourFunction($event)"

Keypress event works on keyUp and keyDown event. Just FYI

Related