phicon
phicon

Reputation: 3617

Angular 2 patchValue in Form Array

i have a form with a form array:

    this.myForm = this._fb.group({
        id: [this.model.id],
        customer_id: [this.model.customer_id],
        orderlines: this._fb.array([])
    });

The form array:

    return this._fb.group({
        id: [orderline.id],
        order_id: [orderline.order_id],
        factor: [orderline.factor],
    })

Now i want to change the value of the factor field within in the method setFactor(i). The i is the index of the form array orderlines.

setFactor(i) {
    this.myForm['orderlines'[i]].patchValue({ factor: 99 }) <--- no error but no change in form
    this.myForm.patchValue({ orderlines[i].factor: 99 }) <-- error

}

How can i use patchValue to change a value in a form array?

EDIT

this will give me the value i want to change:

console.log(this.myForm['controls']['orderlines']['controls'][i]['controls']['factor'].value);

Upvotes: 1

Views: 2378

Answers (2)

Hedgybeats
Hedgybeats

Reputation: 336

First create a method that returns the form array

  GetOrderLinesArray() {
    return this.myForm.get('orderLines') as FormArray;
  }

Then to patch the value:

setFactor(index) {
this.GetOrderLinesArray().controls[index].get('factor').patchValue(99);
}

Upvotes: 0

phicon
phicon

Reputation: 3617

the following worked:

this.myForm['controls']['orderlines']['controls'][i]['controls']['factor'].patchValue(99)

Upvotes: 4

Related Questions