在Angular中将addControl动态添加到FormGroup

addControl to FormGroup dynamically in Angular

如何在Angular中动态地将FormControl添加到FormGroup?

例如,
我想添加一个强制性控件,其名称为" new",其默认值为"。"。


addControl是您所需要的。请注意,第二个参数必须是这样的FormControl实例:

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

如果需要,还可以使用setValidators方法动态添加验证器。调用此选项将覆盖所有现有的同步验证器。


如果您将FormBuilder用于表单,也可以使用它来添加控件:

1
2
3
4
5
constructor(private fb: FormBuilder) { }
   
method() {
  this.testForm.addControl('new', this.fb.control('', Validators.required));
}


简单使用:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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]
      });
    }
}