Angular 2 prevent enter from submitting in template-driven form

后端 未结 9 1588
故里飘歌
故里飘歌 2021-02-01 11:54

I have forms that uses the template-driven blueprint, so something like this:

&
相关标签:
9条回答
  • 2021-02-01 12:29

    This is what helped me:

    • the button that has to act as submitting one should be type="button"
    • that button should have (click)="onSubmit()" <- the method that will be called
    • and you can remove i.e. (ngSubmit)="onSubmit()" from <form [formGroup]="form" (ngSubmit)="onSubmit()">

    I am not sure if there are side-effects of removing (ngSubmit) from the form. BTW: I observed that

    <form (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$event.preventDefault()"></form>
    

    have disabled custom validators.

    0 讨论(0)
  • 2021-02-01 12:31

    To allow enter key to work in textareas but prevent from submitting form, you could modify as follows:

    In HTML template:

    <form (keydown.enter)="handleEnterKeyPress($event)">...</form>
    

    In the component's class in the .ts code behind:

    handleEnterKeyPress(event) {
        const tagName = event.target.tagName.toLowerCase();
        if (tagName !== 'textarea') {
          return false;
        }
      }
    
    0 讨论(0)
  • 2021-02-01 12:33

    Angular 10

    $event.preventDefault() did not work for me - $event.stopPropagation did.

    0 讨论(0)
提交回复
热议问题