Reactive Forms Angular
Template Driven Forms | Reactive Forms |
---|---|
Simple Basic Forms | Complex form with more control. |
Easy to start with | Structure of form is defined in TypeScript class. |
Based on HTML template | |
Angular Reactive Forms
Angular provides two ways to work with forms: template-driven forms and reactive forms (also known as model-driven forms).
In Angular, Template-driven forms are the default way to work with forms in Angular.
In Angular, With template-driven forms, template directives are used to build an internal representation of the form.
With reactive forms, you build your own representation of a form in the component class.
In Angular, Reactive forms also known as Model-driven forms
Reactive forms were introduced with Angular 2
There is no need of Two Way Binding in Angular’s Reactive Forms
Source Code
app.component.ts File Code
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'reactive-forms';
hobbiesArray: string[] = ['Reading', 'Writing', 'Singing'];
signupForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]),
age: new FormControl('', [Validators.required, Validators.min(10), Validators.max(50)]),
email: new FormControl('', [Validators.required, Validators.pattern('^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$')]),
pass: new FormControl('', [Validators.required, Validators.pattern('(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$')]),
gender: new FormControl('', [Validators.required]),
country: new FormControl('', [Validators.required]),
accept: new FormControl(false, [Validators.requiredTrue]),
hobbies: new FormArray([], [Validators.required])
});
onChange(e: any) {
const checkedValue = e.target.value;
const checked = e.target.checked;
console.log(checkedValue, checked);
const checkedArray = this.signupForm.get('hobbies') as FormArray;
if (checked) {
checkedArray.push(new FormControl(checkedValue));
}
else {
let i: number = 0;
checkedArray.controls.forEach((item) => {
if (item.value == checkedValue) {
checkedArray.removeAt(i);
}
i++;
});
}
}
handleSubmit() {
console.log(this.signupForm.value);
}
get f() {
return this.signupForm.controls;
}
}
app.component.html File Code
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="bg-primary p-4 text-center">
<h1>Reactive Forms</h1>
</div>
<form [formGroup]="signupForm" (ngSubmit)="handleSubmit()">
<div class="form-group">
<label for="">Enter Name: </label>
<input type="text" name="name" [class.is-invalid]="f['name'].invalid && f['name'].touched"
class="form-control" formControlName="name">
</div>
<div class="alert alert-danger" *ngIf="f['name'].invalid && f['name'].touched">
<div *ngIf="f['name'].errors && f['name'].errors['required']">
Name Is Required
</div>
<div *ngIf="f['name'].errors && f['name'].errors['minlength']">
3 Characters Minimum
</div>
<div *ngIf="f['name'].errors && f['name'].errors['maxlength']">
20 Characters Maximum
</div>
</div>
<div class="form-group">
<label for="">Enter Age: </label>
<input type="number" [class.is-invalid]="f['age'].invalid && f['age'].touched" name="age" class="form-control"
formControlName="age">
</div>
<div class="alert alert-danger" *ngIf="f['age'].invalid && f['age'].touched">
<div *ngIf="f['age'].errors && f['age'].errors['required']">
Age Is Required
</div>
<div *ngIf="f['age'].errors && f['age'].errors['min']">
Minimum Age is 10
</div>
<div *ngIf="f['age'].errors && f['age'].errors['max']">
Maximum Age is 50
</div>
</div>
<div class="form-group">
<label for="">Enter Email: </label>
<input type="email" [class.is-invalid]="f['email'].invalid && f['email'].touched" name="email"
class="form-control" formControlName="email">
</div>
<div class="alert alert-danger" *ngIf="f['email'].invalid && f['email'].touched">
<div *ngIf="f['email'].errors && f['email'].errors['required']">
Email Is Required
</div>
<div *ngIf="f['email'].errors && f['email'].errors['pattern']">
Invalid Email
</div>
</div>
<div class="form-group">
<label for="">Enter Password: </label>
<input type="text" [class.is-invalid]="f['pass'].invalid && f['pass'].touched" name="pass"
class="form-control" formControlName="pass">
</div>
<div class="alert alert-danger" *ngIf="f['pass'].invalid && f['pass'].touched">
<div *ngIf="f['pass'].errors && f['pass'].errors['required']">
Password Is Required
</div>
<div *ngIf="f['pass'].errors && f['pass'].errors['pattern']">
Please Enter Strong Password
</div>
</div>
<label for="">Gender: </label>
<div class="form-check">
<input type="radio" class="form-check-input" formControlName="gender" name="gender" value="Male">
<label for="">Male</label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" formControlName="gender" name="gender" value="Female">
<label for="">Female</label>
</div>
<div class="form-group">
<label for="">Country: </label>
<select name="country" [class.is-invalid]="f['country'].invalid && f['country'].touched"
formControlName="country" class="form-control">
<option value="">Select</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
</select>
</div>
<div class="alert alert-danger" *ngIf="f['country'].invalid && f['country'].touched">
<div *ngIf="f['country'].errors && f['country'].errors['required']">
Country Is Required
</div>
</div>
<div class="form-check">
<input type="checkbox" formControlName="accept" class="form-check-input" name="accept" id="">
<label for="">I Accept The Terms & Conditions</label>
</div>
<label for="">Hobbies: </label>
<div *ngFor="let hobby of hobbiesArray; let i = index;">
<label for="">
<input type="checkbox" (change)="onChange($event)" class="form-check-input" [value]="hobby" name="hobbies" id="">
{{hobby}}
</label>
</div>
<br>
<div class="d-grid">
<input type="submit" [class.disabled]="signupForm.invalid" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
app.module.ts File Code
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Index.html File Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ReactiveForms</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
</body>
</html>
Download Notes Of This Blog From the link given below
https://www.mediafire.com/file/daooq91225vxkuq/REACTIVE+FORMS+ANGULAR+PPTS.rar/file
No responses yet