Adding controls with validation rules

Let's add a validator to a form control:

this.group['ctrl2'] = new FormControl('',Validators.required)

If you investigate the markup for this newly added form, you can see that indeed its CSS class has been set to ng-invalid due to its value being empty.

Now the next burning question, how do I reference individual elements so I know what errors they may or may not have? The answer is simple, under your form member, of type FormGroup, is a controls dictionary that contains controls. One of these controls works just like a view reference with template forms:

ctrl2 valid {{ form.controls['ctrl2'].valid }}
{{ form.controls['ctrl2'].errors | json }}

As you can see in the preceding code snippet, we can refer to an individual control through form.controls['key']. It has the properties valid and errors on it so we can show individual errors, like so:

<div *ngIf="form.controls['ctrl2'].errors.required">This field is required</div>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset