Search code examples
angularformgroups

How do I set a child formGroup in a formGroup without the initializer?


I'm trying to dynamically set a property in my formGroup to a formGroup; a child formGroup if you will

// Example 1
var parent = this._formBuilder.group({
    id; [''].
    child: this._formBuilder.group({
        name: ['']
    })
})

 

// Example 2
var parent = this._formBuilder.group({
    id; [''],
    child: undefined
})

 

parent.patchValue({'child': this._formBuilder.group({ name: [''] }) })

example 1 will make parent.get('child') return the formGroup. in option 2 however, parent.get('child').value returns the formgroup.

How do I get a dynamically set formGroup to work as if it were set in the formGroup initializer?


Solution

  • patchValue is not for adding a form group or form control but to update the form value.

    To add a form group dynamically, you need to use setControl or addControl.

    parent.setControl('child', this._formBuilder.group({ name: [''] }))