Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to append multiple form controls to form group

I am using the latest version of Angular (v6.0.5).

I have a FormGroup consisting of 3 common controls and based on some logic i want to add other multiple controls to the same FormGroup.

I know i can use this.form.addControl() but i dont want to do this for each individual form control

Is there an easy way to do this?

Example:

this.form = this.formBuilder.group({
    'id': new FormControl('', Validators.required),
    'firstName' new FormControl('', Validators.required),
    'lastName' new FormControl('', Validators.required)
});

if (blah) {
    // Append more FormControls here to same FormGroup
    this.form.addControl('houseNumber', new FormControl(''));
    this.form.addControl('street', new FormControl(''));
    this.form.addControl('postCode', new FormControl(''));
}
like image 818
S edwards Avatar asked Jun 18 '18 10:06

S edwards


People also ask

What is the difference between form control and form group in Angular?

Just as a form control instance gives you control over a single input field, a form group instance tracks the form state of a group of form control instances (for example, a form). Each control in a form group instance is tracked by name when creating the form group.

Can we have nested forms in Angular?

An Angular nested form is a form within a form or, say, the manipulation or creation of a model is different from the parent form model. It allows you to create an array of objects within a single field which sums up to an array of these fields.

What is the difference between FormGroup and FormBuilder?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls. I encourage you to check out those links to see the full class definitions of all three.


1 Answers

For some reason Angular didn't provide API for that case.

You can simply loop over your controls and add it to FormGroup or you can build new FormGroup based on existing:

this.form = this.formBuilder.group({
  'id': new FormControl('', Validators.required),
  'firstName': new FormControl('', Validators.required),
  'lastName': new FormControl('', Validators.required)
});

let blah = true;

if (blah) {
  this.form = this.formBuilder.group({
    ...this.form.controls,
    'houseNumber': new FormControl(''),
    'street': new FormControl('')
  });
} else {
  this.form = this.formBuilder.group({
    ...this.form.controls,
    'otherControl': new FormControl(''),
    'otherControl2': new FormControl(''),
    'otherControl3': new FormControl('')
  });
}

Ng-run Example

like image 72
yurzui Avatar answered Sep 18 '22 09:09

yurzui