1
votes

I have one query in Angular Reactive Form.

I have below formGroup, and inside that formGroup, I have a formArray, and inside that formArray, I have another formGroup. Here is the main formGroup

public formGroup = this.formBuilder.group({
    email: ["", Validators.required],
    address: this.formBuilder.array([
        this.initFun()
    ])
});

Here is the formArray initFun() function

fun() {
    return this.formBuilder.group({
        city: [""],
        state: [""]
    });
}

Now the query is I want to set the validator to city and state dynamically.

What is the approach to add a dynamic validator to formArray inside formGroup?

I can set the validator to email using below syntax:

this.formGroup.controls["email"].setValidators(Validators.required);

But I am not able to set validator for the city and state inside the address array.

Any help would be highly appreciated :)

Update

I've created a sample of the above case you can check out here: https://stackblitz.com/edit/reactive-form-angular

Let me know if I am doing something wrong here.

3
Create a method that return your email controlArray. Do a for loop over the formGroups inside the formArray and use the same method to set the validator like you are doingRicardo
Hi Ricardo, I have tried that method but it doesn't work getting error as below Property 'controls' does not exist on type 'AbstractControl'.Burhan

3 Answers

3
votes

You can iterate over each group in the fb.array and set all the needed validators like this:

let groupItems = this.formGroup.controls["address"].controls;

for(let item of groupItems) {
    item.controls["city"].setValidators(...);
    item.controls["state"].setValidators(...);
}

UPD: To avoid "Property 'controls' does not exist on type 'AbstractControl'" issue, use the following assignment:

let groupItems:any = (this.formGroup.get("address") as FormArray).controls;
1
votes

you can try to get the address FormArray by declaring a method that return it

get address(): FormArray {
  return this. formGroup.get("address") as FormArray;
}

after that you can use the method at to get the specific formGroup inside

this.address.at(index)

after that is just a matter of assigning the Validator to the formControl

UPDATED BASED ON YOUR LINK

your code will look like

  ngOnInit() {
    this.formGroup.controls["email"].setValidators(Validators.required);
    let groupItems = this.formGroup.get("address") as FormArray;;
    groupItems
    for(let index = 0 ; index < groupItems.length; index++ ) {
        groupItems.at(index).get("city").setValidators(Validators.required);
        groupItems.at(index).get("country").setValidators(Validators.required);
    }
  }
1
votes

Thanks to Anna,

Here is the updated answer to my above question. You can refer this link for the reference. https://stackblitz.com/edit/reactive-form-angular

Please ask me if you have any doubts :)