Dynamically addControl to formgroup Angular 5
Sure, but the second parameters should be a FormControl instance. Something like:
this.testForm.addControl('new', new FormControl('', Validators.required));
You can also add the validators dynamically if you want with the setValidators
method.
More information here: https://angular.io/api/forms/FormGroup#addControl
If you are using FormBuilder
for your form, you can also use that for adding a control:
constructor(private fb: FormBuilder) { }
method() {
this.testForm.addControl('new', this.fb.control('', Validators.required));
}
simple use:
this.testForm.addControl('new', this.fb.group({
name: ['', Validators.required]
}));