Andrew Howard
Andrew Howard

Reputation: 3092

Patch value of a form array at a specific index

I have constructed my form like this.

this.myForm = this.fBuilder.group({
  openingHoursForm: this.fBuilder.array([])
});

this.openingHoursArray = data.body.OpeningHours;

this.openingHoursArray.forEach(element => {

(<FormArray>this.myForm.get('openingHoursForm')).push(this.fBuilder.group({
                            Id: [element.Id],
                            Heading: [element.Heading],
                            Subheading: [element.Subheading],
                            When: [element.When],
                            Times: [element.Times],
                            Emphasis: [element.Emphasis],
                            SortOrder: [element.SortOrder]
                    }));
                });

But how do I patch the value of "SortOrder" at a specific index. I have this but it's not working:

moveRowUp(currentIndex,fixture)
    {
        const control = <FormArray>this.myForm.controls['openingHoursForm'];
        control.at(currentIndex)['SortOrder'].patchValue(currentIndex + 1);
        console.log(this.myForm);
    }

Upvotes: 1

Views: 2598

Answers (2)

Andrew Howard
Andrew Howard

Reputation: 3092

There's probably an easier of doing it, but in the end I did it like this:

moveRowUp(fixture)
    {
        var newVal = fixture.controls['SortOrder'].value - 1;
        fixture.controls['SortOrder'].patchValue(newVal);
        console.log(record);
    }

Upvotes: 0

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

try this

 moveRowUp(currentIndex,fixture)
  {
      const control = this.myForm.get(['openingHoursForm',currentIndex,'SortOrder']) as FormControl;
      control.patchValue(currentIndex + 1);

  }

Upvotes: 1

Related Questions