Ionic 将FormGroup推入巢状FormArray

snvhrwxg  于 2022-12-09  发布在  Ionic
关注(0)|答案(1)|浏览(151)

我有一个表单,用户可以在其中填写他们的锻炼。我想调用addSet()并将一个FormGroup推送到sets FormArray

ngOnInit() {
       this.workoutForm = new FormArray([
          new FormGroup({
             name: new FormControl(),
             sets: new FormArray([
                new FormGroup({
                   reps: new FormControl(),
                   weight: new FormControl(),
                }),
             ]),
          })
       ]);
    }
    
     public addSet() {
       this.workoutForm.controls[0].controls.sets.push(
          new FormGroup({
             reps: new FormControl(),
             weight: new FormControl(),
          }),
       )
    }
iq0todco

iq0todco1#

从Angular 文档复制粘贴(根据示例重命名变量):

get sets() {
       return this.workoutForm.get('sets') as FormArray;
    }
    
    addSet(reps, weight) {
       this.sets.push(new FormGroup({
          reps: new FormControl(reps),
          weight: new FormControl(weight),
       }));
    }

https://angular.io/guide/reactive-forms#creating-dynamic-forms

相关问题