Simple Login form using Reactive forms in Angular 7

  Angular

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. Reactive forms differ from template-driven forms in distinct ways. this forms are little complex compare to template driven forms

To use reactive forms, import ReactiveFormsModule from the @angular/forms package and add it to your NgModule’s  imports array.

Don’t Forget to add ReactiveModule in app.module.ts

import {  ReactiveFormsModule } from "@angular/forms";

@NgModule({
declarations: [

],
imports: [
ReactiveFormsModule
],

Example

Reactive-forms.component.html

<form [formGroup]="form" (ngSubmit)="onSubmit(form)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" class="form-control mb-1" formControlName="username" >
<div *ngIf="username.touched && username.invalid" class="alert alert-danger">
<div *ngIf="username.errors.required">* Username required</div>
<div *ngIf="username.errors.minlength">* Username Minimum Length 3</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control mb-1" formControlName="password">
<div *ngIf="password.touched && password.invalid" class="alert alert-danger">
<div *ngIf="password.errors.required">* Password required</div>
<div *ngIf="password.errors.minlength">* Password Minimum Length 6</div>
</div>

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

reactive-forms.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";

@Component({
selector: 'app-reactive-forms',
templateUrl: './reactive-forms.component.html',
styleUrls: ['./reactive-forms.component.css']})
export class ReactiveFormsComponent {


form = new FormGroup({
username: new FormControl('', [Validators.required, Validators.minLength(3)]),
password: new FormControl('', [Validators.required,Validators.minLength(6)])
})

get username(){
return this.form.get('username');
}
get password(){
return this.form.get('password');
}

onSubmit(data){
console.log(data.value)
}
}

Spread the Code

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of