Open In App

How to submit form on pressing Enter with Angular 9?

Last Updated : 05 Nov, 2020
Like Article

To submit a form in angular we have the following options:

  1. Create a button to submit the form.
  2. Assign a key to submit the form
  3. Or we can do both.

In this tutorial, we will see how to use a specific key(Enter in this case) to submit a form.


We can use angular keydown event to use Enter key as our submit key. 

  • Add keydown directive inside the form tag.
  • Create a function to submit the form as soon as Enter is pressed.
  • Assign the keydown event to the function.


Let’s create a form having both, button and Enter key as mode of form submission.

  • We will use bootstrap classes, so add bootstrap scripts in your index.html.


<html lang="en">
        <meta charset="utf-8" />
        <!--add bootstrap script here-->
        <link rel="stylesheet"
              crossorigin="anonymous" />
        <script src=
        <script src=
        <script src=

  • code for the component:


import { Component } from '@angular/core';
@Component({ selector: 'app-root',
//here we used inline template format. template: `
<div style="text-align: center;">
<!--using keydown to assign the event to call EnterSubmit method-->
<form #geeksForm="ngForm"
      (keydown)="EnterSubmit($event, geeksForm.form)"
    <button class="btn btn-primary"
    <input type="text"
           ngModel #geekname="ngModel"
           required minlength="5" />
    <div *ngIf="geekname.errors.required">
        The geek name is required
    <div *ngIf="geekname.errors.minlength">
The geek name should be at least {{
      geekname.errors.minlength.requiredLength }} characters long
    <select class="form-control"
            ngModel #geeksField="ngModel"
        <option *ngFor="let geek of geeks"
            {{ }}
        <div *ngIf="geeksField.touched && !geeksField.valid">
            The category is required
`, styleUrls: [] }) export class AppComponent
      { title = 'Form submission tutorial';
      public name = "geek"; geeks = [ {id: 1, name: "c++geek"},
      {id: 2, name: "pythongeek"}, {id: 3, name: "javageek"},
      {id: 4, name: "javascriptgeek"},
        {id: 5, name: "angulargeek"} ];
 /*assigning EnterSubmit function to keydown event
      and using Enter key to submit the form. */
 //Function will take two parameters:
      //1.The key pressed.
      //2.form. EnterSubmit(event, form) {
          //keycode for
        Enter is 13 if (event.keyCode === 13) {
 alert('Enter key is pressed, form will be submitted');
//calling submit method if key pressed is Enter.
      this.submitit(form); } }
      //function to submit the form submitit(form){
alert("The form was submitted"); form.reset(); } }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads