Submitting the form by pressing Enter key in Angular
In this tutorial, we are going to learn about how to submit the form by pressing an enter key inside the input
field in angular.
See this example code.
<div>
<form (ngSubmit)="handleSubmit($event)"">
<input placeholder="Enter message" name="msg" [(ngModel)]="msg" />
<button type="submit">Submit</button>
</form>
</div>
In the above code, we have a form with an input
field and submit
button and the form can be only submitted by clicking the submit
button.
Now, let’s see how to submit the above form by pressing an enter key.
Using the keyup event
The keyup event occurs when a user releases the key (on keyboard).so that by adding this event inside the input
field we can submit a form by pressing the enter key.
The keyCode
for the Enter key is 13
.
<div>
<form (ngSubmit)="handleSubmit($event)" >
<input placeholder="Enter message" name="msg" [(ngModel)]="msg"
(keyup)="handleKeyUp($event)" /> <button type="submit">Submit</button>
</form>
</div>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
msg = '';
handleSubmit(e){
e.preventDefault();
alert(this.msg);
}
handleKeyUp(e){ if(e.keyCode === 13){ this.handleSubmit(e); } }
}
In the above code, we have added the keyup
event with handleKeyUp()
method to the input
field.
Inside the handleKeyUp()
method, we are using if
conditional to check if an enter
is pressed; then only we are submitting the form, otherwise we are not doing anything.
Note: If you have more than one input
field in your form then you need to add keyup
event to the last input
field.