Andrew Howard
Andrew Howard

Reputation: 3072

Angular 2 Turn form control into form group later

I have a form array with a control called "foreground" which is null to start with:

(<FormArray>this.myForm.get('rooms')).push(this.fBuilder.group({
                id: [element.id, [Validators.required]],
                background: null,
                foreground: null,
            }));

But how can I turn it onto a form group with fields under it later on? I tried this:

room.controls.foreground(this.fBuilder.group({
                foregroundImageID: [null, [Validators.required]],
                foregroundImagePath: [null, [Validators.required]],
                foregroundXPosition: [null, [Validators.required]],
                foregroundYPosition: [null, [Validators.required]]
            }));

Upvotes: 0

Views: 82

Answers (2)

Jameer Khan
Jameer Khan

Reputation: 413

You can do it something like below:

(<FormArray>this.myForm.get('rooms')).push(this.fBuilder.group({
    id: [element.id, [Validators.required]],
    background: null,
    foreground: null
}));

Now SetControl like this-

this.myForm.controls.rooms['controls'][0].setControl('foreground', this.fBuilder.group({
      foregroundImageID: [null, [Validators.required]],
      foregroundImagePath: [null, [Validators.required]],
      foregroundXPosition: [null, [Validators.required]],
      foregroundYPosition: [null, [Validators.required]]
}));

Note: setControl replaces the existing control. learn more about setControl

Upvotes: 1

Soumya Gangamwar
Soumya Gangamwar

Reputation: 1022

Build your form like this

(<FormArray>this.myForm.get('rooms')).push(this.fBuilder.group({
                id: [element.id, [Validators.required]],
                background: null,
                foreground: this.fBuilder.array([]),
            }));

Here Now foreground working as Array, With that you can push elememts into foreground

Upvotes: 1

Related Questions