Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_weight and total_gross_weight. I am trying to bind the values of net_weight and gross_weight in the parcelForm so that when a user adds a new instance of parcelForm and enters values for these form controls, it will update the total_net_weight and total_gross_weight in the orderForm. I have attempted to use functions like patchValue without success.

This code block is from new-order.page.ts:

import { Component, OnInit } from '@angular/core';
// other imports...

@Component({
  selector: 'app-new-order',
  templateUrl: './new-order.page.html',
  styleUrls: ['./new-order.page.scss'],
})
export class NewOrderPage implements OnInit {
  @Output() formChange = new EventEmitter();
  pageTitle: string;
  orders: Order[];
  // rest of the declarations...

  constructor(
    private orderService: OrderService,
  ) { }

  ngOnInit() {
    // initialization code...
  }

  onSubmit() {
    // form submission logic...
  }
  
  // other methods...

}

The HTML content from new-order.page.html:

<ion-header>
  <ion-toolbar color="dark">
    <ion-title>{{pageTitle}}</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-row>
    <ion-col size-md="8" offset-md="2">

      <form [formGroup]="orderForm">        
        <!-- form elements... -->
      </form>
      <br>
      <br>

      <ion-row>
        <ion-col size="4" offset="10">
          <ion-button color="success" (click)="addParcelButtonClick()">
            <ion-icon name="add-outline"></ion-icon>Add Parcel
          </ion-button>
        </ion-col>
      </ion-row>
      <form [formGroup]="parcelForm">
        <div formArrayName="parcels">
          <div *ngFor="let parcel of parcels().controls; index as parcelIndex;">
            <div [formGroupName]="parcelIndex">
              Parcel {{parcelIndex + 1}}:
              <ion-item>
                <ion-label position="floating">Net Weight</ion-label>
                <ion-input type="text" formControlName="net_weight"></ion-input>
              </ion-item>
              <ion-item>
                <ion-label position="floating">Gross Weight</ion-label>
                <ion-input type="text" formControlName="gross_weight"></ion-input>
              </ion-item>
              <br>
              <ion-row>
                <ion-col size="4" offset="10">
                  <ion-button color="danger" (click)="removeParcel(parcelIndex)">Remove <ion-icon name="trash-outline">
                    </ion-icon>
                  </ion-button>
                </ion-col>
              </ion-row>
            </div>
          </div>
        </div>
      </form>


    </ion-col>
  </ion-row>
</ion-content>

Answer №1

The values were retrieved in the following manner:

this.parcelForm.get('parcels').get([this.iterator, 'net_weight']).valueChanges.subscribe(
      data => this.total_net_weight += data
    );

No changes were required on the frontend.

Here is how my addParcelButtonClick() function ended up:

  async addParcelButtonClick() {
    this.parcels().push(this.newParcelFormGroup());
    this.iterator = this.number_of_parcel;
    let gross_weight = 0;

    this.parcelForm.get('parcels').get([this.iterator, 'net_weight']).valueChanges.subscribe(
      data => this.total_net_weight += data
    );
    this.parcelForm.get('parcels').get([this.iterator, 'gross_weight']).valueChanges.subscribe(
      data => {
        this.total_gross_weight += data;
        gross_weight = data;
      }
    );


    this.getOrderFormValues();
    this.number_of_parcel++;

  }

This is the getOrderFormValues() function:

getOrderFormValues() {
    this.orderForm.setValue({
      total_net_weight: this.total_net_weight,
      total_gross_weight: this.total_gross_weight
    });
  }

And here is the removeParcel function:

async removeParcel(parcelIndex: number) {
    // this.iterator = this.number_of_parcel;
    if (this.parcelForm.get('parcels').get([parcelIndex, 'net_weight'])) {
      this.total_net_weight -= await this.parcelForm.get('parcels').get([parcelIndex, 'net_weight']).value;
      this.total_gross_weight -= await this.parcelForm.get('parcels').get([parcelIndex, 'gross_weight']).value;

    }
    this.parcels().removeAt(parcelIndex);
    this.number_of_parcel--;
    this.getOrderFormValues();
  }

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

Obtain the PHP function output through asynchronous JavaScript and XML programming

I have a form that collects user input and saves it to the database. After submitting the form, an ajax call is made to the action.php file. e.preventDefault(); $.ajax({ type: "POST", url: "action.php", data: senData, dataType: "JSON", ...

Tips on preventing Realtime database onWrite trigger function callback from iterating through data that has been altered

I am currently developing a 1 vs 1 game matching system using a real-time database. The system works by creating a record in the users table when a user signs in. Once there are two players with a status of placeholder, a cloud function generates a gameInf ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

Leverage socket.io in various routes within a node.js application

In my Node.js application, I have various routes defined in the router.js file. Now, I want to implement socket.io in every route to enable real-time communication between my Node.js and React.js applications. However, the structure of my Node.js applicati ...

What are some ways to make source code more visually appealing on an HTML/JSP page as it is being

I've recently created a webpage with some Java source code, neatly organized within blocks. However, I'm looking to enhance its appearance so it truly looks like Java code. Take a look at my page's code here for reference: Are there any onl ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Switch the text display by clicking on a different button in the list

I am currently dealing with an issue involving a list of boxes containing text/images and buttons for expanding/collapsing the text. Whenever I click on another item's button, the text box that was previously opened gets closed, but the button text re ...

Utilize setState in a ReactJS function within an if statement towards the end

Help needed! I'm facing issues trying to use the function setState within an if statement inside another function. Specifically, I'm working on creating a series of Tab components with inline styles that determine their visibility. Before returni ...

Ways to prevent scrolling on mobile web browsers?

I am currently facing an issue with disabling scrolling on a webpage when a user opens a popup, while still allowing them to scroll within the popup itself. The popup element is defined by the following attributes: #popup { display: none; width: ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

What is the proper way to reference the newly created type?

I came up with a solution to create a custom type that I can easily use without the need to constantly call useSession(), as it needs to be a client-side component. However, whenever I try to access this custom type, it always returns undefined (if I try t ...

Is the $http call for OPTIONS instead of POST?

Hey there, I'm encountering a strange issue while trying to call my backend using the POST method. Remote Address:192.168.58.183:80 Request URL:http://192.168.58.183/ESService/ESService.svc/CreateNewAccount Request Method:OPTIONS Status Code:405 Meth ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Exploring the concept of asynchronous subscriptions in Angular

My current issue seems to be related to asynchronous programming, specifically with the subscription not running at the desired time. I typically approach this problem from both the user's and developer's perspectives. User's Perspective: ...

"Missing the import of material-ui search icons is causing a functionality issue

import React from 'react' import {Search} from "@material-ui/icons/Search" const App = () => { return ( <div> <Search/> </div> ) } export default App The exported component 'Search' (impor ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

Employing promises for retrieving ajax data

I've been struggling to make sure my code waits for an ajax call to finish before proceeding, as I need data in an array first. No matter what I try, it seems like promises might be the best solution in this scenario. Currently, the ajax call still oc ...