[Fixed] How to append new FormGroup or FormControl to form

Issue

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?

Solution

You can use addControl method of FormGroup class as per documentation

So you can do as below :

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

Leave a Reply

(*) Required, Your email will not be published