1

I create a formArray inside form in angular.

When I patch object that has tasks with values as array, seems that this property is ignore and not set.

as expected, the firstname is changed. but the tasks not. why?

I don't want to catch the specific element and use setValue or something similar, I just want to have an object and angular will investigate this object and match the values and the fields.

The code in stackblitz.com

import { Component, VERSION } from "@angular/core";
import { FormGroup, FormControl, FormArray } from "@angular/forms";

@Component({
  selector: "my-app",
  template: `
    <form [formGroup]="profileForm">
      {{ profileForm.value | json }}

      <br /><br /><br />
      <label>
        First Name:
        <input type="text" formControlName="firstName" />
      </label>

      <label>
        Last Name:
        <input type="text" formControlName="lastName" />
      </label>

      <button type="button" (click)="clickme()">clickme</button>
    </form>
  `
})
export class AppComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(""),
    lastName: new FormControl(""),
    tasks: new FormArray([])
  });

  clickme() {
    this.profileForm.patchValue({
      firstName: "foo",
      tasks: [false, true, false]
    });
  }
}
2

1 Answer 1

2

As stated in to the documentation:

A FormArray :

Tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances.

A FormArray is meant to be an array of controls, not of values. You can only patchValues to existing formControls.

In your situation, if you want to patch [false, true, false], you need to define your tasks FormArray as tasks: new FormArray([new FormControl(), new FormControl(), new FormControl()]), so you have 3 controls ready to be populated.

Another solution would be to loop over your array to push a new FormControl with the value new FormControl(data[x]) for each item.

const tasks = [true, false, true];

tasks.forEach(task => {
  this.profileForm.controls.tasks.push(new FormControl(task));
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.