0

I need that a button inside a dialog responds to the key.enter event.

I have searched and all the examples are buttons that are inside a <form> which is not the case

Do I need to put the button inside a "dummy form" for this to work? can I do that without losing the current button style

This is what I have tried...

<mat-dialog-actions class="buttons">
    <button mat-button mat-dialog-close (click)="onCancelClick()">
        {{data.cancel}}
    </button>
    <button class="action nonDefault" mat-button mat-dialog-close color="accent" class="action"
        (click)="cancelOrClose()" (keyup.enter)="cancelOrClose()">
        {{data.cancelOrClose}}
    </button>
</mat-dialog-actions>

Hitting enter with the dialog open does nothing

similar questions that I have found

Angular 5 Button Submit On Enter Key Press

angular 2 material keyup.enter does not fire at all

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99

1 Answers1

5

You need autofocus and (keyup.enter) on the button so that it processes the key events

<button class="action nonDefault" #btnFocus [autofocus]="btnFocus.focus()" mat-button
    (keyup.enter)="cancelOrClose()" (click)="cancelOrClose()" mat-dialog-close>
    {{data.cancelOrClose}}
</button>
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99