Saving three different forms with just a single submission using Angular 10

Trying to simultaneously save 3 forms of an angular stepper, where the products (secondFormGroup) and values(thirdFormGroup) may contain multiple rows.

The API model is structured as follows:

{
  "product": [
    {
      "description": "string",
      "id": 0,
      "name": "string",
      "priority": 0,
      "store": {
      "id": 0,
      "name": "string",
      "type": "PROPERTIES",
      "version": 0
    },
    "values": [
      {
        "id": 0,
        "value": "string"
      }
     ]
    }
  ],
  "store": {
    "id": 0,
    "name": "string",
    "type": "PROPERTIES",
    "version": 0
  }
}

Below is a snippet of my code:

@Input() firstFormGroup!: FormGroup;
@Input() secondFormGroup!: FormGroup;
@Input() thirdFormGroup!: FormGroup;
@Input() products!: IProduct[];
@Input() values!: IValue[];

constructor(private _formBuilder: FormBuilder) {

  this.firstFormGroup = this._formBuilder.group({
   name: ['', Validators.required],
   type: ['', Validators.required],
  });


  this.secondFormGroup = this._formBuilder.group({
   name: ['', Validators.required],
   description: ['', Validators.required],
   priority: ['', Validators.required],
  });

  this.thirdFormGroup = this._formBuilder.group({
   value: [null, [Validators.required]],
  });

}

This is my service method:

createStore(storeInfo: IStore): Observable<EntityResponseType> {
  return this.http.post<IStore>(this.CSstoreUrl, storeInfo, { observe: 'response' });
 }

If anyone could assist with resolving a persistent 400 error, it would be greatly appreciated.

Here is a snapshot from the network tab that might provide insights

Answer №1

Have you ever considered consolidating all your stepper forms into a single nested group or array using formArray? Here's an example (refer to the documentation for accurate syntax):

this.fullForm = this._formBuilder.group({ // This will follow the structure of IStore
    store : this.firstFormGroup,
    product : this._formBuilder.array([ 
        this._formBuilder.group({ 
            name: ['', Validators.required],
            description: ['', Validators.required],
            priority: ['', Validators.required],
            values: this._formBuilder.array([ 
                this._formBuilder.control('', Validators.required)
            ])
        })
    ])
    
})

By doing this, the form will generate a value object that aligns with the API structure.

this.fullForm.value // Reflects the forms' structure without disabled ones
this.fullForm.valueChanges.subscribe(change => console.log(change)) // Logs every value change

To further debug, you can include this in your template:

<pre>{{fullForm.value | json}}</pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for ngIf to only hide the div without impacting the overall layout?

I utilize a left side menu and main content. <div class="row"> <div ngIf="loginUser" class="sidebar col-md-3> ....... </div! <div class="main col-md-9> ....... </div> </div> It is hidden when ...

Invalid Type Property - Request and Response Express Types

When I try to utilize the Request or Response types in this manner: app.use('*', (req: Request, res: Response, next: NextFunction) => { res.set('Cache-Control', 'no-store'); const requestId: string = req.headers[&a ...

Encountering an issue with installing an angular 2 directive, getting a error message "Cannot read property '0' of

I am attempting to install this using the command prompt like so: PS C:\Users\moshel\Workspaces\Aman.Magar.Maply\WebUI> npm install @ngui/auto-complete --save However, I am receiving the following outcome: npm WARN @angular/[ ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

Creating an extended class in Typescript with a unique method that overrides another method with different argument types

I need to change the argument types of a method by overriding it: class Base { public myMethod(myString: string): undefined { return; } } class Child extends Base { public myMethod(myNumber: number): undefined { return super.m ...

How can you adjust the size of focused elements like autocomplete or datepicker in Angular Material 15?

I recently updated to Material 15 and I'm wondering how I can adjust the height or overall size of focused components like autocomplete or datepicker. The page mentioned that density cannot be used on such components, so what other methods are availa ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

What is the best approach to apply type casting in an *ngFor loop for an array containing a variety of types in Angular?

I am facing a scenario where I have two objects named DeviceA and DeviceB, both belonging to the same parent class called Device. interface Device { shared: string } interface DeviceA extends Device { attributeA: string[] } interface DeviceB extends ...

MAJOR UPDATE: webpack versions before 5 previously contained polyfills for node.js specifically for 'timers-browserify'

Hey there, I'm encountering the error message below: ./node_modules/xml2js/lib/parser.js:38:17-47 - Error: Module not found: Error: Can't resolve 'timers' in '/Users/differentname/Desktop/workfiles/webdoc/ngx-admin-1/node_modules/x ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Expanding the Element prototype with TypeScript

Is there a corresponding TypeScript code to achieve the same functionality as the provided JavaScript snippet below? I am looking to extend the prototype of the HTML DOM element, but I'm struggling to write TypeScript code that accomplishes this with ...

Angular Checkbox Click EventLearn how to handle click events on

How can I toggle the visibility of a form using ngIf when a click event is triggered by a checkbox? Below is the code for my column header and column values: <th><label class="btn btn-filter"> <input type="checkbox" ...

The Type X is lacking essential properties found in Type Y, including length, pop, push, concat, and an additional 26 more properties. Code: [2740]

One interesting thing I have noticed is the Product interface: export interface Product{ code: string; description: string; type: string; } There is a service with a method that calls the product endpoint: public getProducts(): Observable<Product ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

retrieving dynamic information from beyond the subscribe function

In order to implement canActivate for user routes, I need to first verify the validity of the access token. Below is the approach I am taking: export class AuthGuard implements CanActivate { data:Array<Object>; constructor(private base: BaseServ ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

Different ways to contrast rows within ag-grid

I am in the process of comparing two identical rows within my ag-grid and emphasizing any variances between them. While most column values are matching, I wish to highlight any cell that differs from the previous row. Is there a means to achieve this in ...

Tips for generating a hyperlink in a Typescript file using Angular version 16 and above

I am encountering an issue with my consts.ts file in the project. Specifically, I have defined a constant LINK1 as <a href='https://sample.com/'>LINK 1</a>; However, this setup is not working as expected. What I actually want is to d ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...