Prevent form submission on enter key

后端 未结 15 1257
夕颜
夕颜 2020-12-05 06:24

How can I prevent the enter key from submitting the form in angular?

Is there a way to catch the 13 key and disable it or set the form as invalid unless submitting f

15条回答
  •  無奈伤痛
    2020-12-05 06:44

    The following should work . . . i.e., the form is only submitted on button click, and not on hitting Enter in the Input boxes. (This definitely works for reactive forms. I didn't test it for template forms).

    Of course, remember all the imports and declarations:

    app.module.ts

    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [
    . . .
        FormsModule,
        ReactiveFormsModule
    
      ]
    . . . 
    })
    export class AppModule { }
    

    test.component.ts

    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss']
    })
    export class TestComponent {
      form: FormGroup = new FormGroup({});
      constructor() { }
    
    }
    
    

提交回复
热议问题