Guide to Reactive Forms in Angular
Reactive forms provide a model-driven approach to handling form inputs whose values change over time. In Angular, reactive forms are a powerful way to manage user input within the framework. This guide covers the basics of creating and validating reactive forms in Angular and provides some tips for working with them.
Creating Reactive Forms
Reactive forms can be created in two ways: using the FormBuilder
class or the FormGroup
and FormControl
classes. The FormBuilder
class is the easiest way to create a reactive form and is recommended for most cases. To use it, first import the ReactiveFormsModule
into your component.
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
]
})
export class AppModule { }
Then use the FormBuilder
to create a form group and its controls. A form group is a collection of form controls and is used to track the value and validation state of a group of form controls. A form control is an individual input field and tracks the value and validation state of the field.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required],
age: [null, [Validators.required, Validators.min(18)]],
});
}
}
In the example above, the form group has two controls: name
and age
. The name
control is required, while the age
control is required and must be at least 18.
Validating Reactive Forms
Reactive forms are automatically validated when the user interacts with the form. To validate the form, you must specify validators for the form controls. Validators are functions that take a control instance and return either null if the value is valid or an error object if the value is invalid. In the example above, the name
control is required and the age
control is required and must be at least 18.
You can also use custom validators to provide more complex validations. For example, to check if two form fields have the same value, you can use the Validators.compose
method to compose two validators together:
const sameValueValidator = Validators.compose([
(control: AbstractControl) => {
const value = control.value;
const otherValue = control.root.get('otherFieldName').value;
if (value !== otherValue) {
return {
sameValue: true
};
}
return null;
}
]);
this.form = this.fb.group({
name: ['', Validators.required],
age: [null, [Validators.required, Validators.min(18)]],
otherFieldName: ['', Validators.required],
sameValue: ['', sameValueValidator]
});
Submitting Reactive Forms
To submit a reactive form, use the FormGroup
instance's submit
method. This method will trigger the form's validation and return a Promise
that resolves to true
if the validation is successful and false
if it fails.
this.form.submit().then(isValid => {
if (isValid) {
// submit the form
} else {
// show errors
}
});
Tips for Working with Reactive Forms
- Use the
FormBuilder
class to create reactive forms, as it simplifies the process. - Use the
FormGroup
instance'ssubmit
method to submit the form, as it triggers the validation and returns aPromise
. - Use custom validators to provide more complex validations.
- Use the
FormGroup
andFormControl
classes to create and validate reactive forms, if needed.
Reactive forms are a powerful way to create and validate forms in Angular. With the information provided in this guide, you should be able to create and validate reactive forms with ease.