How can I add a FormControl to a FormGroup dynamically in Angular?
For example, I would like to add a mandatory control which name is "new" and its default value is ''.
How can I add a FormControl to a FormGroup dynamically in Angular?
For example, I would like to add a mandatory control which name is "new" and its default value is ''.
addControl
is what you need. Please note the second parameters must be a FormControl instance like so:
this.testForm.addControl('new', new FormControl('', Validators.required));
You can also add the validators dynamically if you want with the setValidators
method. Calling this overwrites any existing sync validators.
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]
});
}
}