0

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?

1
  • you have to pass array of control name in this.fb.array([], validateGroupItem(this.myCollection)) to this.fb.array([{'controlName' : ' '}], validateGroupItem(this.myCollection)) Commented Nov 26, 2019 at 5:52

2 Answers 2

1

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()]
});
Sign up to request clarification or add additional context in comments.

Comments

0

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> 
      ...

1 Comment

No I want to access the values so I can use the value in the validator class. I need to do this before I use *ngIf="item.invalid". In the validateGroupItem function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.