首页 > 解决方案 > Is it possible to add property dynamically to groupform

问题描述

Is it possible to add property dynamically to groupform? I need a property name to have an index as part of the name

createForm() {
    for (let index = 0; index < 10; index++) {
        this.groupForm = this.fb.group({
            prixName+index: ['', [Validators.maxLength(4)]],
        });


    }
}

标签: angularforms

解决方案


为此使用 addControl 函数

this.testForm.addControl('new', new FormControl('', Validators.required));

在 Angular 中动态查看这个答案addControl to FormGroup和这个链接https://angular.io/api/forms/FormGroup#addcontrol

createForm() {
   this.groupForm = this.fb.group({});
   for (let index = 0; index < 10; index++) {
     this.groupForm.addControl(prixName+index, new FormControl(null, Validators.maxLength(4)));

   }
}

如果您需要表单控件数组,请使用 FormArray 而不是索引或增量计数器。在这种情况下,这也将对您有所帮助 https://angular.io/api/forms/FormArray


推荐阅读