Рет қаралды 89,467
In this tutorial, we will see how to create reactive forms in Angular 8 using Formcontrol and FormGroup.
The basic requirement for setting up the reactive forms is importing the ReactiveFormsModule in the app.module
1.FormControl:
In FormControl, we can create the instance of the formcontrol in the component class.
For eg.
email = new FormControl('');
Here we have created a instance of the FormControl in the component class named as Email.
And in the Html, we can use the created instance for creating the html element.
We can access this FormControl in the component class to get or set the value.
For eg: this.email.setValue('test@testdomain.com');
2.FormGroup :
The FormGroup is nothing but the collection or a group of FormControls.
For eg :
userprofileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
age: new FormControl(''),
email:new FormControl(''),
});
Here, we are defining a FormGroup named as "userprofileForm". In this formgroup, we have 4 controls named as firstname,lastName,
age and email.
we can declare them in the same fashion in the html .
And in the form element , we just have to name the formgroup.
eg: [formGroup]="userprofileForm"
How to access the formControl within the formgroup :
For eg:
this.userprofileForm.controls 'firstName'].value
So here we are accessing the formControl named as "firstName" in the fromgroup named as "userprofileForm".
Form Control Validation:
We have to import the Validators from the '@angular/forms' for incorporating the validators in the control.
userprofileForm = new FormGroup({
firstName: new FormControl('',Validators.required),
....
});
Here we are making the firstName formcontrol as mandatory.
The FormGroup has a inbuilt property named as valid.
eg : userprofileForm.valid
Here "userprofileForm" is the formgroup. userprofileForm.valid will be true if the form passes all the validations on the form successfully.
Else it will return false.
#Angular #Angular 8 #Angular 10 #Angular 12 #Angular 13 #Angular 15