In this blog post, we will learn to use Angular Reactive Forms value change detection and enable conditional validation on basis of that.
Let us say you have a Reactive Form created using FormBuilder class as shown below:
You have created loginForm, which has three controls: email, password, and phonenumber. Here, you are using FormBuilder to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormBuilder.
We have also put error messages for email and phone number fields. Besides, that submit button would only be enabled when the form is valid. Form submit is handled as shown in the listing below:
If the form is valid in browser console, you will get the output as below:
In addition, if there is an error, submit button would be disabled and an error message will be shown as below:
Now assume a scenario that you have a radio button to send a notification. The user should able to select the send notification option, and on basis of that, certain FormControl will have some validation.
Consider the form below,
We have added a Send Notification option. If the user selects Phone to send notification then Phone Number field should be required, otherwise, it should not be. To achieve this we need to perform following tasks,
- Listening to changes
- Put conditional validation
To start with, let us modify our form to handle the notification. So now form has a notification FormControl with the default value set to null as shown in the listing below :
On the Reactive form template, we will add radio button group to handle Send Notification option.