简体   繁体   中英

Patch value to multiple formArray in Angular reactive forms

Not able to patch multiple formArray in a formGroup.

Form

 this.usersForm = this.fb.group({
      users: this.fb.array([
        {
          firstName: [""],
          lastName: [""],
        }
      ]),
      work: this.fb.array([
        {
          workType: [""],
          workTitle: [""],
        }
      ]),
    });

I have multiple formArray like these, how to patchValue to it. I tried the below approach but it makes the code too redundant

const formArray = new FormArray([]);

    data.work.forEach((s) => {
      formArray.push(
        this.fb.group({
          workType: s.workType,
          workTitle: s.workTitle,
        })
      );
    });

this.usersForm.setControl("work", formArray);
//get form array control
let a = this.usersForm.get('work') as FormArray;

// push control in above form array
a.push(this.fb.group({
      workType: 'workType value',
      workTitle: 'workTitle value'
});

or if you want to use patchValue then

this.usersForm.patchValue(your json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM