Author -  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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY