I have a simple angular form, for example:
<form [formGroup]="form">
<div>
<input type="text" (keydown.enter)="onEnterPerssed($event)" [formControl]="myList" formControlName="myList">
</div>
<br>
<p *ngIf="sendData" class="mt-1">Data send successfully</p>
<button type="submit" (click)="onSubmit(form)" class="btn btn-block btn-primary mt-2" style="width: 100px;" [disabled]="form.invalid">
Submit
</button>
</form>
export class AppComponent implements OnInit {
sendData: boolean = false;
form: FormGroup;
isDisabled: boolean = true;
myList: FormControl = new FormControl('sdfsdf', [Validators.required ]);
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.form = this.fb.group({
myList: this.myList
});
}
onSubmit(form): void {
this.sendData = true;
console.log('data send successfully');
}
onEnterPerssed(event: Event) {
event.stopPropagation();
console.log('asdasfasfsfafasfasf');
}
}
Is there any solutions on how to prevent submitting form while we click Enter on the input field, without changing button type (submit => button)
Change submit event on form
tag, and remove click event from submit button.
<form [formGroup]="form" (ngSubmit)="onSubmit($event)">
onSubmit(event) {
event.preventDefault();
// logic goes here
}
ngSubmit
ensures that the form doesn’t submit when the handler code throws (which is the default behaviour of submit) and causes an actual http post request.