I have used angular mat-stepper to implement a form of multiple steps. The first step is one form and there are 3 such steps. Something like this:
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
thirdFormGroup: FormGroup;
fourthFormGroup: FormGroup;
rows: FormArray;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.firstFormGroup = this.formBuilder.group({
name : ['', Validators.required],
gender : ['', Validators.required]
});
this.secondFormGroup = this.formBuilder.group({
permanentHouseName: ['', Validators.required],
permanentHouseNumber: ['', Validators.required],
permanentPlace: ['', Validators.required]
});
this.thirdFormGroup = this.formBuilder.group({
profession : ['', Validators.required],
designation : ['', Validators.required],
});
I want to submit all 3 forms at once on click of submit at the last third step. I am able to access the data of the forms individually but is there any way we can submit it as one form data to my java spring controller in backend.
Access to data:
submit() {
if (this.basicInfoForm.valid) {
console.log(this.firstFormGroup.value);
}
console.log(this.secondFormGroup.value);
}
CodePudding user response:
If you can access the form individually, then you can combine the values into 1 object & then send it to your backend.
const combinedValue={
...this.firstFormGroup.value,
...this.secondFormGroup.value,
...this.thirdFormGroup.value
};
Here, we used the spread operator to extract all values of the individual form & made a new object out of it. You can use this object to send to backend.
CodePudding user response:
You can submit all 3 forms by using a spread operator Spread Operator Syntax which allows us to expand an iterable like array or object into its individual elements.
submit() {
if (this.firstFormGroup.valid && this.secondFormGroup.valid &&& this.thirdFormGroup.valid) {
const data = {
...this.firstFormGroup.value,
...this.secondFormGroup.value,
...this.thirdFormGroup.value
};
// Continue with your submit operation
}
}
