将formGroup推向嵌套的formarray

发布于 2025-02-08 17:39:57 字数 722 浏览 1 评论 0原文

我有一种表格,用户可以填写他们的锻炼。我想调用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(),
          }),
       )
    }

I have a form where the user can fill out their workout. I'd like call addSet() and push a FormGroup to the 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(),
          }),
       )
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落花浅忆 2025-02-15 17:39:57

copy-paste(根据您的示例重命名变量)来自角文档:

    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

Copy-paste (By renaming the variables according to your example) from angular docs:

    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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文