Angular 将控件动态添加到窗体组中

Angular 将控件动态添加到窗体组中,angular,angular-reactive-forms,form-control,Angular,Angular Reactive Forms,Form Control,如何在Angular中向FormGroup动态添加FormControl 比如说,, 我想添加一个名为“new”且默认值为“”的强制控件。是您需要的。请注意,第二个参数必须是FormControl实例,如下所示: this.testForm.addControl('new',new-FormControl('',Validators.required)); 如果希望使用该方法,还可以动态添加验证器。调用此函数将覆盖任何现有的同步验证器。如果您正在对表单使用FormBuilder,也可以使用此函

如何在Angular中向FormGroup动态添加FormControl

比如说,, 我想添加一个名为“new”且默认值为“”的强制控件。

是您需要的。请注意,第二个参数必须是FormControl实例,如下所示:

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

如果希望使用该方法,还可以动态添加验证器。调用此函数将覆盖任何现有的同步验证器。

如果您正在对表单使用
FormBuilder
,也可以使用此函数添加控件:

构造函数(私有fb:FormBuilder){}
方法(){
this.testForm.addControl('new',this.fb.control('',Validators.required));
}
简单使用:

  this.testForm.addControl('new', this.fb.group({
      name: ['', Validators.required]
    }));

这也有帮助:就像Siro回答了您的问题一样,您可以使用addControl方法向表单组添加新的输入。我有一个研究动态形式的小项目。我希望这是有用的。在值更改订阅中添加控件时如何停止事件发出?抱歉,如何包含多个验证程序,例如this.testForm.addControl('new',new FormControl('',[Validators.required,Validators.max(100)]);
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.scss']
})
export class ComponentName implements OnInit {

    formGroup: FormGroup;        
    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
       this.formGroup = this.formBuilder.group({
        firstName: new FormControl('', Validators.required),
        lastName:  new FormControl('', Validators.required),
      });    
    }
    
    // Add single or multiple controls here
    addNewControls(): void {
      this.formGroup = this.formBuilder.group({
         ...this.formGroup.controls,
         email: ['', Validators.required],
         phone: ['', Validators.required]
      });
    }
}