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.ts
file and import theValidators
artifact from the@angular/forms
npm package:
import { FormControl, FormGroup, Validators } from '@angular/forms';
- Modify the declaration of the
productForm
property so that eachFormControl
instance passesValidators.required
as a second parameter:
productForm = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: Validators...