doe
doe

Reputation: 455

How to validate FormGroups in a FormArray

How can I validate each FormGroup in a FormArray? Here I have the custom validator:

export class GridProcessorValidator {

  static validateGroupItem(definition: ObjectDefinition) {
      return function(control: AbstractControl): ValidatorFn {
          return null;
      };
  }

}

And here is the form:

this.gridProcessorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    groupItems: this.fb.array([], validateGroupItem(this.myCollection))   // array of form groups that needs custom validation
});

How can I access the values of FormGroups within the custom validator definitionPropertiesMatched so I can check it then print it to the template for individual FormGroups that are invalid?

Template:

*ngFor="let item of gridProcessorForm.get('groupItems').controls; let i=index"
                    [formGroupName]="i"> ...

Then I have form field accessor:

{{item.get('propertyName').value}}

Is there a way I can get any errors for an item (FormGroup) in the iterator?

Upvotes: 0

Views: 1079

Answers (2)

Bilel-Zheni
Bilel-Zheni

Reputation: 1312

Inside your html access each form group state through the loop template input variable, in your case 'item' :

   *ngFor="let item of gridProcessorForm.get('groupItems').controls; let i=index"
                    [formGroupName]="i"> 
      ...

   <div *ngIf="item.invalid" class="text-danger"> Invalid !</div> 
      ...

Upvotes: 0

Eliseo
Eliseo

Reputation: 57929

If you write

this.fb.array([], validateGroupItem(this.myCollection))

You're validate the whole formArray, then your validators function can be like

static validateGroupItem(definition: ObjectDefinition) {
      return function(control: FormArray): ValidatorFn {
          return null;
      };
  }

If you want a validator over each group of your array, you need add the validator when push a formGroup in the array,e.g.

createGroup()
{
    return this.fb.group({
      name:''
      surname:''
    },validateGroupItem(this.myCollection))
}

And you use

this.gridProcessorForm.get('groupItems') as FormArray.push(this.createGroup())

Or

this.gridProcessorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    groupItems: this.fb.array([this.createGroup(),this.createGroup()]
});

Upvotes: 1

Related Questions