Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change FormBuilder array items in nested forms

According to the API documentation the proper way to change nested values is to use method patchValue

myForm.patchValue({'key': {'subKey': 'newValue'}});

But how to change values in nested arrays like list of cars in this example below. How to get first item of list array an change model to Fiesta? Plunker

myForm.patchValue({'list': 0: {'model': 'Fiesta'}); is not working.

@Component({
  moduleId: __moduleName,
  selector: 'my-app',
  template: `<div><pre>{{ myForm.value | json }}</pre></div>`
})
export class AppComponent {

  public myForm: FormGroup;

  constructor(@Inject(FormBuilder) private _fb: FormBuilder) {

    this.myForm = this._fb.group({
      name: 'Cars',
      list:  this._fb.array([
        this.initCar(),
        this.initCar(),
        this.initCar()
      ]),
    });
    /** Change value Here **/
    this.myForm.patchValue({name: 'Automobile'});
  };

  initCar() {
    return this._fb.group({
      automaker: 'Ford',
      model:     'Fusion'
    });
  }
}

Plunker

like image 472
khex Avatar asked Aug 22 '26 10:08

khex


1 Answers

I did something similar not that long ago just add.

const patchV = (<FormArray>this.myForm.controls['list']).at(0) as FormArray;
patchV.patchValue({automaker: 'CoolCar', model: 'Bucket'})

Working Example [plunker]http://embed.plnkr.co/VWicnA/

like image 116
edumas000 Avatar answered Aug 25 '26 02:08

edumas000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!