

Blog
Published On - February 3, 2020
In this article we discuss how to create forms using [formGroup] directive. We need to first import “ReactiveFormsModule” from ‘@angular/forms’ in module file “app.module”.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
.............
@NgModule({
imports: [
ReactiveFormsModule,
.........
]
.......
})
Lets create login form using validation using “ReactiveFormsModule” module.
import { Component ,OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
loginForm: FormGroup;
submitted:boolean = false;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
get v() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
}
}
Below is the code for template.
<div>
<div>
<div>
<h2>Login</h2>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div>
<label>Email</label>
<input type="text" formControlName="email" [ngClass]="{ 'is-invalid': submitted && v.email.errors }" />
<div *ngIf="submitted && v.email.errors">
<div *ngIf="v.email.errors.required">Email is required</div>
<div *ngIf="v.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div>
<label>Password</label>
<input type="password" formControlName="password" [ngClass]="{ 'is-invalid': submitted && v.password.errors }" />
<div *ngIf="submitted && v.password.errors">
<div *ngIf="v.password.errors.required">Password is required</div>
<div *ngIf="v.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div>
<button [disabled]="loading">Login</button>
</div>
</form>
</div>
</div>
</div>
Below is the full embeded code.
Tags:
Leading software development company. We specialize in web and mobile application development.
We are strategists. We are innovators. We are a team of full-stack enterprise and mobile app developers
Office Address
B-680, 2nd Floor,
Green Field Colony, Faridabad
121010
Haryana, India
Phone: +91 93133 54455
