0

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]]
            }));

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Also how would I set that "foreground" back to null later on?
Glad I could help :)
Do you how how would I set that "foreground" back to null later on? :)
You can just remove the control like- this.myForm.controls.rooms['controls'][0].removeControl('foreground')
Hmm I got an error of "Cannot read property 'value' of undefined" doing it that way.
1

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

2 Comments

Thanks but it has to start as null to begin with. I can't start with it being an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.