How to append new FormGroup or FormControl to form

smartmouse picture smartmouse · Jan 11, 2017 · Viewed 65.2k times · Source

I have the following form in Angular created with FormBuilder:

constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
        'name': ['', [Validators.required],
        'surname': ['', [Validators.required],
        'email': ['', [validateEmail]],
        'address': fb.group({
            'street': [''],
            'housenumber': [''],
            'postcode': ['']
        }, { validator: fullAddressValidator })
    });
}

Does exist a way to programmatically append new fields such as FormControl or new FormGroup to myForm ?

I mean if I want to add new fields on demand or on some conditions, how to add items to the same form that is created the first time in the constructor?

Answer

ranakrunal9 picture ranakrunal9 · Jan 11, 2017

You can use addControl method of FormGroup class as per documentation

So you can do as below :

this.myForm.addControl('newcontrol',[]);