Nijoo
Nijoo

Reputation: 1

How to append a formgroup to another?

I have two formgroups :firstFormGroup and secondFormGroup

firstFormGroup is in mat step 1 and secondFormGroup is in mat step 2. Now while posting it to the backend, I want to append secondFormGroup to the firstFormGroup

How to achieve this?

Upvotes: 0

Views: 329

Answers (1)

Vladimir Prudnikov
Vladimir Prudnikov

Reputation: 7242

You can get values from these forms and merge them into one dictionary using Object.assign.

const data = Object.assign({}, firstFormGroup.value, secondFormFroup.value);

Also, you can use nested form groups

export class MyComponent implements OnInit {

  form = new FormGroup({
    first: new FormGroup({
      name: new FormControl('')
    }),
    second: new FormGroup({
      name: new FormControl('')
    })
  });
  constructor() { }

  ngOnInit() {
  }

}

then in template

<form [formGroup]="form.get('first')"></form>
<form [formGroup]="form.get('second')"></form>

this way you will not loose any data even if you have controls with the same key on multiple steps and you have only one form to work with and validate.

Upvotes: 1

Related Questions