Angular 2 having the form builder to build the login form with the validation, Here we see a simple login form with the validation.
Lets first create a html component with the user name and password form
<div class="row">
<div class="col-md-offset-4 col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<h2 class="text-center text-muted">Login</h2>
<form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)">
<div class="form-group" [ngClass]="{'has-error':!loginForm.controls['user_name'].valid && loginForm.controls['user_name'].touched}">
<label for="username">User Name</label>
<input type="text" name="user_name" class="form-control" id="username" placeholder="User Name" [formControl]="loginForm.controls['user_name']" />
<small *ngIf="loginForm.controls['user_name'].hasError('required') && loginForm.controls['user_name'].touched" class="text-danger">Username Required</small>
</div>
<div class="form-group" [ngClass]="{'has-error':!loginForm.controls['password'].valid && loginForm.controls['password'].touched}">
<label for="password">Password</label>
<input type="password" name="username" class="form-control" id="password" placeholder="Password" [formControl]="loginForm.controls['password']" />
<small *ngIf="loginForm.controls['password'].hasError('required') && loginForm.controls['password'].touched" class="text-danger">Password Required</small>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-default" [disabled]="!loginForm.valid">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
The html component is created, now lets create the ts component for this form.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'login-section',
templateUrl:'login.component.html'
})
export class LoginComponent {
loginForm: FormGroup;
constructor(fb: FormBuilder){
this.loginForm = fb.group({
'user_name': [null, Validators.required],
'password': [null, Validators.required]
});
}
login(value){
if(this.loginForm.valid){
console.log("Login form valid");
}
}
}
Thats it, we have created the login form with validation, now register this component in the app.module and use the selector <login-section></login-section> to see the login form.
No comments:
Post a Comment