addControl to FormGroup dynamically in Angular

AngularAngular Reactive-FormsForm Control

Angular Problem Overview


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 ''.

Angular Solutions


Solution 1 - Angular

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.

Solution 2 - Angular

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));
}

Solution 3 - Angular

simple use:

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

Solution 4 - Angular

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]
      });
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoeSmithView Question on Stackoverflow
Solution 1 - AngularSiroView Answer on Stackoverflow
Solution 2 - AngularAT82View Answer on Stackoverflow
Solution 3 - AngularTrilok SinghView Answer on Stackoverflow
Solution 4 - AngularImFarhadView Answer on Stackoverflow