99
votes

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

4
Like Siro answered your question, you can use addControl method to add new inputs to your form group. I have a little project wich studied dynamic forms. I hope which be useful. stackblitz.com/edit/angular-eypxbq?embed=1&file=src/app/…Michael Charles

4 Answers

202
votes

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.

49
votes

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

simple use:

  this.testForm.addControl('new', this.fb.group({
      name: ['', Validators.required]
    }));
1
votes
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]
      });
    }
}