klmuralimohan
klmuralimohan

Reputation: 931

Angular 8 Form Array controls not working on selection

Trying to pass the selected country to get the respective states to bind into the sibling dropdown. Unfortunately it is throwing an error.

What is wrong in the code. Kindy suggest.

HTML

<form [formGroup]='entityForm'>
              <div formArrayName="optionGroups" class="ui-g ui-g-12 ui-g-nopad " >
                <div  class="ui-g  ui-g-12 ui-g-nopad " *ngFor="let item of entityForm.controls['optionGroups'].controls; let $index=index" [formGroupName]="item">

 <select formControlName="country" class="ui-inputtext" (change)="onCountryChange(entityForm.controls['optionGroups'].controls[$index].controls['country'].value, $index)" > 
                  <option>--Select--</option>
                  <option *ngFor="let c of countries" [ngValue]="c.value">{{c.label}}</option>
                 
                </select>

 <select formControlName="state" class="ui-inputtext"> 
                  <option>--Select--</option>
                  <option *ngFor="let state of states[entityForm.controls['optionGroups'].controls[$index].controls['country'].value]" value="state.value">{{state.label}}</option>
                 
                </select>

</div>
                </div>

Angular 8 - TS

public countries = [];
public states = [];

public entityForm: FormGroup;
constructor() {

this.entityForm = this.fb.group({
    optionGroups : this.fb.array([
        this.fb.group({
          country : [],
          state : [],

      }),
   ])

this.countries = [{"label":"United States","value":"US"},{"label":"Canada","value":"CA"}];
this.states=[];    
}

 onCountryChange(selectedCountry: string , formIndex : number) : void {    
      this.states[selectedCountry] = this.getStates(selectedCountry)      
    }

Error During country selection

enter image description here

Upvotes: 0

Views: 166

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

You try to access the array's formGroups with [formGroupName]='item'. item, however, is not a name, but an object (a FormGroup). That is the object you see in console. Please change it to [formGroup]='item'

Upvotes: 1

Related Questions