简体   繁体   中英

Angular 7 Reactive forms - link form group in FormArray to object

I'm creating a formarray of formgroups

const skillsControl = <FormArray>this.form.controls['skills'];

this.selectedCourse.requiredSkills.forEach(skill => {
    const s = this.fb.group({
                instructor: ['', Validators.required],
                ...other controls...
              });
    skillsControl.push(s);
}

Each selectedCourse will have a unique set of skills.

I need to be able to display the name of the skill, and then the form controls associated to that skill.

How do i associate the required skill object with its respective form group?

You have to define your form in this way:

  const items = new FormArray(this.skills.map(item => new FormGroup({
                name: new FormControl(item.name),
                instructor: new FormControl(item.instructor)
  })));

  this.myForm = new FormGroup({items: items});

I did a full example in stackblitz:

Form Array exmple

I hope it helps!

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