Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views5 pages

Introduction To Reactive Forms

Uploaded by

sanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Introduction To Reactive Forms

Uploaded by

sanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to Reactive Forms

11 April 2023
00:25

Version

Angular CLI: 15.1.6


Node: 18.12.1
Package Manager: npm 9.5.0

Forms handling is a fundamental component of many popular apps.


Applications make use of forms to make it possible for users to carry out a variety of data entry
operations.

Angular has 2 ways to handle user input:


1. Reactive Forms
2. Template Driven Forms

In this tutorial we will be building this form using Reactive Form where user can enter information
like name, email, password and confirm password.

Unlike template-driven forms, which perform control in the template, reactive forms allow us to
implement logic, validations, and controls in the components class section of the code.

The flexible reactive form can be applied to any complex form scenario. Unit testing is made simpler
by the fact that we write more component code and less HTML code.

Overview
11 April 2023
00:54

Reactive forms manage a form's state at a certain point in time using an explicit and immutable
method.
The model's integrity is preserved between changes because every modification to the form state
results in a new state.

Import module
The ReactiveFormsModule must first be imported in authenticate.module.ts.

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

...
imports: [

ReactiveFormsModule,
],

To get a basic understanding of Formgroup and FormControl, let us go to our sign-up.component.ts
file

FormControl
A view input is represented by a FormControl.
The default value is the first parameter, and the second is a validator for this field (or an array of
validators).

FormGroup
FormGroup is made consisting of a map with an AbstractControl as its value (which means either a
FormControl, FormGroup or FormArray). To construct a complex value, we can nest our FormGroup.
If necessary, we may additionally add more form-level validators after the map.

FormControl: https://angular.io/api/forms/FormControl
FormGroup: https://angular.io/api/forms/FormGroup

Form creation and validation


11 April 2023
01:31

In our sign-up.component.ts file we will create one function createSignUpForm() which we will call in
our ngOnInit function

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

signupForm: FormGroup;

ngOnInit(): void {
this.createSignUpForm();
}

private createSignUpForm() {
this.signupForm = new FormGroup({
email: new FormControl('', [Validators.required,
Validators.email]),
password: new FormControl('', [Validators.required,
Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$
%^&*-]).{8,}$')]),
confirmPassword: new FormControl('', [Validators.required,
Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$
%^&*-]).{8,}$')]),
displayName: new FormControl('', Validators.required),
});
}

Now we can access the form value anytime by using this.signUpForm.value


As you can see above we have used 3 different basic validators, Required, email and a pattern where
we provide the regex pattern.

To get the value from the signup form on submit button click we will create signUp() function in our
sign-up.component.ts file
We have simply checked if the form is valid and if valid then print the forms data in console and if
the form is invalid then print invalid data in console as error.

signup() {
if (this.signupForm.valid) {
console.log(this.signupForm.value);
} else{
console.error('invalid data');
}
}
}

Sign Up HTML page


11 April 2023
01:45

Now in our sign-up.component.html file we will be creating html elements to consume the
formcontrols created

Here we have added form and given the formGroup to it as signUpForm declared in our ts file
In the input we have added formControlName and specified the formcontrol name created in our
createSignUpForm() function

<form [formGroup]="signupForm">
<div class="grid">
<div class="col-12">
<div class="card flex justify-content-center">
<p-card header="Sign up" [style]="{ width: '360px' }">
<!-- <ng-template pTemplate="header">

</ng-template> -->
<ng-template pTemplate="content">
<div>
<label for="username">Name</label>
<div>
<input
class="w-100"
pInputText
formControlName="displayName"
type="text"
placeholder="Name"
/>
</div>
</div>
<div class="mt-3">
<label for="username">Email</label>
<div>
<input
class="w-100"
pInputText
formControlName="email"
type="text"
placeholder="Email"
/>
</div>
</div>
<div class="mt-3">
<label for="password">Password</label>
<div>
<input
class="w-100"
pInputText
type="password"
formControlName="password"
placeholder="Password"
/>
</div>
</div>
<div class="mt-3">
<label for="password">Confirm Password</label>
<div>
<input
class="w-100"
pInputText
type="password"
formControlName="confirmPassword"
placeholder="Confirm Password"
/>
</div>
</div>
</ng-template>
<ng-template pTemplate="footer">
<div class="flex justify-content-center align-items-
center">
<button
pButton
pRipple
label="Sign up"
(click)="signup()"
></button>
</div>
<div class="mt-2 flex justify-content-center align-items-
center">
<p-button
label="Already have an account? Click Here"
styleClass="p-button-link"
routerLink="/login"
></p-button>
</div>
</ng-template>
</p-card>
</div>
</div>
</div>
</form>

Simplify with FormBuilder


11 April 2023
01:49

We can utilise a magical API that does everything for us rather than utilising FormGroup and
FormControl directly. Hence, importing FormGroup and FormControl won't be necessary; all that will
need to be imported is the FormBuilder.

In our sign-up.component.ts file in the constructor add FormBuilder

constructor(private fb: FormBuilder) {}

Replace the new FormGroup and new FormControl with this.fb.group and this.fb.control
respectively.

private createSignUpForm() {
this.signupForm = this.fb.group({
email: this.fb.control('', [Validators.required,
Validators.email]),
password: this.fb.control('', [Validators.required,
Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$
%^&*-]).{8,}$')]),
confirmPassword: this.fb.control('', [Validators.required,
Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$
%^&*-]).{8,}$')]),
displayName: this.fb.control('', Validators.required),
});
}

FormBuilder provides a single API which can be imported and used in place of using FormGroup and
FormControl api

All the other things will work same as we have created using FormGroup and FormControl

We have now got a better understanding of FomrGroup, FormControl and FormBuilder.

Hope you liked the tutorial


Follow for more. ❤️

You might also like