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 validation rules, we use the second parameter of the FormControl constructor:
- Open the
product-create.component.tsfile and import theValidatorsartifact from the@angular/formsnpm package:
import { FormControl, FormGroup, Validators } from '@angular/forms';
- Modify the declaration of the
productFormproperty so that eachFormControlinstance passesValidators.requiredas a second parameter:
productForm = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: Validators...