HDTuto.com

Disable Enter Key on Submit Form in Angular



Now, let's see post of disable enter key submit form angular. i explained simply step by step angular disable enter key submit. it's simple example of how to prevent enter key in angular. I’m going to show you about how to disable enter key in angular.

Here, i will show how to stop submit form using enter key in angular 6, angular 7, angular 8 and angular 9 application.

I will give you very simple example for prevent form submit using disabled in angular. bellow simple solution:

<button type="submit" [disabled]="!form.valid">Submit</button>

Now we will see full example then you can understand how it works. let's see bellow:

Import FormsModule:

src/app/app.module.ts

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({

imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

Template Code:

In this step, we will write code of html form with ngModel. so add following code to app.component.html file.

I used bootstrap class on this form. if you want to add than then follow this link too: Install Boorstrap 4 to Angular 9.

src/app/app.component.html

<div class="container">

<h1>How to check form is valid or not in Angular - HDTuto.com</h1>

<form [formGroup]="form" (ngSubmit)="submit()">

<div class="form-group">

<label for="name">Name</label>

<input

formControlName="name"

id="name"

type="text"

class="form-control">

</div>

<div class="form-group">

<label for="email">Email</label>

<input

formControlName="email"

id="email"

type="text"

class="form-control">

</div>

<strong>Result:</strong>

<pre>{{ form.valid }}</pre>

<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>

</form>

</div>

updated Ts File

src/app/app.component.ts

import { Component } from '@angular/core';

import { FormGroup, FormControl, Validators} from '@angular/forms';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

form = new FormGroup({

name: new FormControl('', [Validators.required, Validators.minLength(3)]),

email: new FormControl('', [Validators.required, Validators.email])

});

submit(){

console.log(this.form.valid);

if(this.form.valid){

console.log(this.form.value);

}

}

}

Now you can run your application using following command:

ng serve

Output

true

{name: "hardik", email: "hardik@gmail.com"}

Let's see bellow layout:

I hope it can help you...




April 28, 2020 | Category : Angular



Blog Search


Copyright © 2020 HDTuto.com. All rights reserved.