by Sai gowtham

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.

app.component.html
<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.

app.component.html
<div>
<form (ngSubmit)="handleSubmit($event)" >
   <input placeholder="Enter message" name="msg" [(ngModel)]="msg"
   (keyup)="handleKeyUp($event)" />   <button type="submit">Submit</button>
 </form>
</div>
app.component.ts
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course