Saturday 2 February 2019

Angular formarray validation

Angular formarray validation



In this topic we will discuss validating FormArray in Angular. 

  • FormArray can contain form controls, form groups or nested form arrays.
  • In our case, the "skills" form array, contains form groups. Each form group contains, 3 form controls.angular formarray invalid
  • If all the 3 form controls are valid, then the form group is valid
  • If all the form groups are valid, then the form array is valid.
  • Even if a single form control in a form group is invalid, then the form array is invalid.

Here is what we want to do. Until, all the skill related form controls are properly filled and valid, we want to keep "Add Skill" button disabled.  

angular formarray validation 

This is very easy to achieve. We already know, even if a single form control is invalid, the entire form array is invalid. So to keep the "Add Skill" button disabled, bind the button disabled property to "skills" form array invalid property as shown below. 

<button type="button" class="btn btn-primary"
        (click)="addSkillButtonClick()"
        [disabled]="employeeForm.get('skills').invalid">
  Add Skill
</button>

While we are here, let's also include an <hr> element to separate each skills form group. 

angular formarray disable 

We want the <hr> element to be generated, only if we have more than 1 skills form group, hence we have bound *ngIf directive on the <hr> element to i>0 

<div formArrayName="skills"
     *ngFor="let skill of employeeForm.get('skills').controls; let i = index">
  <hr *ngIf="i>0">
  <div [formGroupName]="i">

In the CSS file, include the following style for the <hr> element 

hr {
    border1px solid silver;
}

No comments:

Post a Comment