addControl to FormGroup dynamically in Angular
Asked Answered
D

7

151

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

Disadvantaged answered 30/11, 2017 at 12:41 Comment(2)
that could also help: #55334783Predominate
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/…Hosbein
C
301

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.

Caramel answered 30/11, 2017 at 13:16 Comment(4)
Sorry, how do to includo more that one validator, for example this.testForm.addControl('new', new FormControl('', [Validators.required, Validators.max(100)]);Provocative
Works like a charm.Ground
For me I needed to add formGroup: FormGroup to the type in order for this to work in Angular 14.Sniff
Note that you can add several validators using an array: this.testForm.addControl('name', new FormControl('', [Validators.required, Validators.max(5)]))Ethic
P
70

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));
}
Preliminaries answered 28/1, 2019 at 9:6 Comment(1)
how to stop event emit when adding control inside a value change subscription?Europium
W
11

simple use:

  this.testForm.addControl('new', this.fb.group({
      name: ['', Validators.required]
    }));
Watteau answered 6/3, 2020 at 11:32 Comment(0)
G
6

Angular 14 added typings to forms. Here is what the new syntax looks like:

Form declaration

public form = new FormGroup<{ new?: FormControl<string | null> }>();

Note that the new control must be declared as optional. You won't be able to use addControl if the field isn't declared first.

For a bigger form you can use an interface:

interface MyForm {
    field1: FormControl<string | null>;
    field2: FormControl<string | null>;
    new?: FormControl<string | null>;
}

public form = new FormGroup<MyForm>({
    field1: new FormControl<string | null>('', Validators.required),
    field2: new FormControl<string | null>('', Validators.required),
});

Add control to the form

this.form.addControl('new', new FormControl<string | null>('', Validators.required));
Get answered 23/10, 2022 at 9:2 Comment(0)
C
3
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]
      });
    }
}
Chartist answered 7/1, 2021 at 6:58 Comment(0)
F
3

I was facing the same problem in Angular 12. Following code snippets worked perfectly for me.

Declare the form:

public form: FormGroup;

Create a new control for the form:

this.form.addControl('new', new FormControl('', Validators.required));
Fils answered 22/5, 2022 at 19:3 Comment(1)
This answer worked for me since Angular 14 now made the form groups require types.Sniff
M
1

To add a new FormControl dynamically to only one instance of an existing FormArray, use the casting technique.

form: FormGroup;

constructor(private fb: FormBuilder){
  this.form = this.fb.group({
    formArrayName: this.fb.array([])
  });
} //

addNewFormArrayInstance(insertIndex: number){
  // insertIndex to insert at a specific position
  const NEWFORMGROUP = new FormGroup({
    'control1': new FormControl(''),
    'control2': new FormControl({value: [], disabled: true}),
    'control3': new FormControl('', Validators.required),
    'control4': new FormControl(true)
  });

  // use push(NEWFORMGROUP) if needed
  (<FormArray>this.form.get('formArrayName')).insert(insertIndex, NEWFORMGROUP);
} //

addControlToFormArrayInstance(index: number){
  // index is the FormArray instance's index to which a new control is to be added
  (<FormGroup>
    (<FormArray>this.form.get('formArrayName')).controls[index]
  ).addControls(
    'newControl', new FormControl('new')
  );
} //
Misadvise answered 7/2, 2023 at 11:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.