How to Validate FormArray length in angular2

Chandra Shekhar picture Chandra Shekhar · Feb 12, 2017 · Viewed 43.8k times · Source

I have a data driven form in angular2 like below

this.formBuilder.group({
  'name': ['',Validators.required],
  'description': ['', Validators.required],
  'places': this.formBuilder.array([], Validators.minlength(1)) 
})

I want to add validations to the place formArray, so i am adding minlength validation, but minlength validation is not working on formArray.

What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.

Answer

Javier González picture Javier González · Nov 9, 2017

Validators.required does the magic for you:

// using required 

this.formGroup = this.formBuilder.group({
    taskTreeId: [Common.UID()],
    executionProgrammedTime: ["", [Validators.required]],
    description: [""],
    tasks: this.formBuilder.array([], Validators.required)
});  

// using custom validation

export const minLengthArray = (min: number) => {
  return (c: AbstractControl): {[key: string]: any} => {
    if (c.value.length >= min)
      return null;

    return { MinLengthArray: true};
  }
}

 this.formGroup = this.formBuilder.group({
        taskTreeId: [Common.UID()],
        executionProgrammedTime: ["", [Validators.required]],
        description: [""],
        tasks: this.formBuilder.array([], minLengthArray(2))
    });
<button type="button" class="btn btn-success btn-rounded" 
    [disabled]="!formGroup.valid">SAVE</button>