addControl to FormGroup dynamically in Angular
如何在Angular中动态地将FormControl添加到FormGroup?
例如,
我想添加一个强制性控件,其名称为" new",其默认值为"。"。
1 | this.testForm.addControl('new', new FormControl('', Validators.required)); |
如果需要,还可以使用
如果您将
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] }); } } |