Merging Data from Multiple Forms in an Angular Application

I am currently working on my first Angular project and although I have made significant progress, I have reached a point where I feel I need assistance to complete it successfully.

Project Overview: I have a class mod.ts

export interface Mod {
    id : number ,
    name? : string,
    clauseList? : Clause
    country? : string;
    company? : string;
    process? : string;
}

export interface Clause {
    cName? : string,
    cid? : number,
    // pc : number,
    parentC?  :number,
    id? : number,
    text? : Text
}


export interface Text {
    txt? : string,
    tid? : number
}

This is the structure of the form data that will be sent to the backend by the user, with values coming from two different forms named clauseForm and filterForm. The filterForm consists of radio buttons from 4 different arrays, while the clauseForm contains 3 input fields.

I have included a stackblitz demo link for reference.

Here is the process flow: The user selects values from the radio buttons and saves them as an object for later use. Then, the user clicks on the edit form and fills in the fields. Upon clicking "add" in this form, a div should display the text entered in the "txt" field, and simultaneously, all data should be pushed into finalPostArray to be sent to the server. This is my current approach, but I'm open to alternative suggestions. I am struggling with how to combine data from the two forms into one object to send to the server. Any assistance or clarification on this matter would be greatly appreciated.

Stackblitz has been updated. Please refer to the README.txt for more details.

Answer №1

If you're looking to combine form data from two different objects, you can achieve it like this:

finalData = {};

saveData(form: NgForm) {
   this.show1 = true;
   Object.assign(this.finalData, form.value);
}

addData(filter: NgForm) {
   Object.assign(this.finalData, filter.value);
   filter.reset();
} 

Depending on your specific scenario, you can decide when to send this data to the backend.


UPDATE:

If you need to merge the data into a single object, use the following:

finalPostArray = [];
mergedObj = {};

saveData(form: NgForm) {
   ... 
   Object.assign(this.mergedObj, form.value);
   this.finalPostArray.push(this.mergedObj);
   ... 
}

addData(filter: NgForm) {
   Object.assign(this.mergedObj, filter.value);
   filter.reset();
}

Check out the working example on StackBlitz

Answer №2

If you want to combine data from form1 and form2, you can create a new array called finalData to store the accumulated data. When the user clicks on the save button, you can send the data from finalData.

  form1Data = [];
  form2Data = [];
  finalData = [];

  saveClause(form  :NgForm){
    console.log("Form Values",form.value);
    this.form1Data = form.value;
    this.show1 = true
  }

  addFilter(filter : NgForm){
    console.log("FilterForm Value",filter.value)
    this.form2Data = filter.value;
    this.finalData.push({
      ...this.form1Data,
      ...this.form2Data
    });

    console.log(this.finalData);

    filter.reset()
  }

Check out the working demo here : link

Important: Remember to view the console for the final result.

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

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...

ng-model to interact with dynamically loaded elements

My dynamic list contains various items, such as cars, and is not of fixed length. Upon loading, the list appears as follows: itemList = [ { id: 0, name: 'bmw' }, { id: 1, name: 'audi' }, { id: 3, name: 'vw' }, ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...

Steps for inserting a clickable phone number link within innerHTML1. First, create an

I've been trying to include a specific phone number using the <a href> tag within the innerHTML. I attempted using both double and single quotes. In the first case, nothing happens at all. In the second case, although the phone number appears, ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

Utilizing Angular to Transform an Array of Dates

I have an array of dates which returns: [Mon Aug 03 2020 00:00:00 GMT+0100 (British Summer Time), Wed Aug 05 2020 00:00:00 GMT+0100 (British Summer Time)] I am looking to convert these into the following format: ["2020-02-13T02:39:51.054", &quo ...

The observable did not trigger the next() callback

I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions: import { Injectable } from '@angular/core'; import ...

Employing an object from a distinct module

After creating a function to parse objects and provide getters, I encountered an issue. I need to access this object from a different module without re-parsing it each time. Is there a way to achieve this without using a global variable? var ymlParser = r ...

Technique for transferring information between properties of a class instance within an Express server's architecture

I am in the process of developing a monitoring server for a library using Express. My goal is to create different routers and routes, while also being able to access functions and variables from the monitor-server class. Currently, I have passed the ' ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

Creating a new library that relies on Ionic 2 and Angular 2 with Dependency Injection

Let me set the stage for our current dilemma: Within my team, we are in the process of developing an Ionic 2 application that comes in various customer-specific versions. Despite sharing similar functionalities, these versions differ in settings, names, a ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Ways to assign scores to every response button

Below is an excerpt of code that showcases a list of potential answers for each question in the form of checkbox buttons. The task at hand is to assign marks to each answer button, which can be retrieved from the database. Marks for correct answers are obt ...