1
votes

I have implemented a functionality like, while click of enter key on any where in form it should hit submit button. Now this functionality is working fine, but problem is on top of my form one modal window will open for some scenario. On that window If user click enter it is hitting background form submit button. Here I'm expecting until closing modal it shouldn't hit to submit button. Here I'm unable to control Enter key on modal.

This is my code snippet:

@HostListener('document:keydown', ['$event'])
  keyboardInput(event: KeyboardEvent) {
    this.onKeydown(event);
  }
  
  onKeydown(event:KeyboardEvent):void {
    if (event.keyCode === 13) { 
    this.submit();
    }
  }
2

2 Answers

1
votes

You need to modify your condition to check whether the modal is open or not as

if (event.keyCode === 13 && isModalOpen)  //maintain the state of modal in isModalOpen property
    this.submit()
else
    this.modalSubmit();
0
votes

IMK, by default, the default action of an Enter key event in a form is to submit the form. You don't have to do anything extra for this.

To prevent form submition when the modal is open, stop the propagation of the key enter event. Lets say that the very outermost HTML element of the modal is a div, the you add the following to the div

<div (keydown.enter)="$event.stopPropagation()"></div>