Home > Blockchain >  How can I update value of child formcontrol in Angular
How can I update value of child formcontrol in Angular

Time:10-05

I have one formcontrol like event and event in 2 more form control like city and state. So how can I update value of city and state ( There are multiple city and state ) my form group example:

In starting I declared event form control

this.dataform = this.fb.group({ event: new FormArray([]) });

then dynamically I add city and state form control

const field: FormArray = (this.dataform.get('event') as FormArray);
field.push(
      new FormGroup({
        city: new FormControl('', [
          Validators.required
        ]),
        state: new FormControl('', [
          Validators.required
        ])
      })
    );

So how can I update value of city and state formcontrol

event:[ { "city": "", "state": "" }, { "city": "", "state": "" } ]

CodePudding user response:

a quick Search leads i.e. to Angular 2: Accessing data from FormArray

So you can use something like this where '1' is the index:

form.get('event.1').patchValue(...)
or
form.controls.list.at(1).patchValue(...)
or
form.get('event').at(1).patchValue(...)

Havent tried the latter but basically its about getting the control that you want to update and then setting it. Since its a FormArray, you need to access it by the index.

  • Related