Validating controls in a reactive way
We have already learned how to apply validation to the template of a form. We used the required
attribute in the Using reactive patterns in Angular forms section to indicate that an input control needs to have a value. In reactive forms, the source of truth is our form model, so we need to be able to define validation rules when building the FormGroup
instance.
To add a validation rule, we will use the second parameter of the FormControl
constructor
:
- Open the
reactive-login.component.ts
file and add theValidators.required
method to theusername
andpassword
form controls:loginForm = new FormGroup({ username: new FormControl('', Validators.required), password: new FormControl('', Validators.required) });
- The
Validators
class
contains almost the same validator rules that are available for template-driven forms, such as therequired
validator....