How to Resolve Angular 2 Reactive Forms Problem the Angular Native Approach, not using jQuery

Utilizing Angular 2 Reactive Forms alongside Typescript, my template structure is as follows:

<form [formGroup]="form">
    <div class="M">
        <div class="X">
            <!-- I would like to avoid adding (change)="onChanged()" on all inputs -->
            <input class="A" formControlName="MXA" /> 
            <input class="B" formControlName="MXB" />
            <input class="C" formControlName="MXC" />
        </div>
        <div class="Y">
            <input class="A" formControlName="MYA" />
            <input class="B" formControlName="MYB" />
            <input class="C" formControlName="MYC" />
        </div>
    </div>
    <div class="N">
        <div class="X">
            <input class="A" formControlName="NXA" />
            <input class="B" formControlName="NXB" />
            <input class="C" formControlName="NXC" />
        </div>
        <div class="Y">
            <input class="A" formControlName="NYA" />
            <input class="B" formControlName="NYB" />
            <input class="C" formControlName="NYC" />
        </div>
    </div>
</form>

Accompanied by the component class:

export class MyCompoenent {

  public form: FormGroup;

  onInit() {
    this.form = new FormGroup({
      MXA: new FormControl(),
      MXB: new FormControl(),
      MXC: new FormControl(),
      MYA: new FormControl(),
      MYB: new FormControl(),
      MYC: new FormControl(),
      NXA: new FormControl(),
      NXB: new FormControl(),
      NXC: new FormControl(),
      NYA: new FormControl(),
      NYB: new FormControl(),
      NYC: new FormControl(),
    });

    this.form.valueChanges.subscribe((p) => {
      /* Unsure which input has been altered here */
    });
    this.form.get('MXA').valueChanges.subscribe((p) => {
      /* Prefer not to subscribe to each individual input like this, especially with numerous inputs */
    });

  }

}

My goals are as follows:

1. There are four divs each containing three inputs; these inputs are related by the equation A+B=C. When one input is altered, it should check if another input in the same div has a provided value, and if so, calculate the third input accordingly.

For instance, if the value of input M => X => A is 2 and the user enters 3 in M => X => B, then M => X => C should automatically be set to 5.

2. If one input changes, it should update another input within the SAME grandparent div that shares the same class.

For example, if the value of input M => X => A is set to 5, then 5 should also be set in the input M => Y => A.

In the context of jQuery, achieving this is simple as a single binding can be applied to all inputs, allowing navigation within the DOM from the triggered input. However, I am seeking the proper Angular approach. The use of this.form.valueChanges() doesn't specify the changed input, and I am reluctant to subscribe to each input individually or add bindings to every input within the Angular template. I want to avoid excessive work, and refrain from using methods like getElementsByClassName, which is more familiar in jQuery. Any suggestions?

Thank you for your assistance!

Answer №1

By defining formControlName in each input field, you can easily monitor any changes that occur. Accessing the value of the form control can be done as follows:

this.form.get("formControleName");

Alternatively, you can establish a form control and subscribe to it for changes:

filterName = new FormControl(null);
constructor(){
  this.filterName.valueChanges.subscribe(value => {
    if (value) 
  }
}

There is another option available, though it is not recommended:

  <input #inputAX (change)="aChanged(inputBX)"/> 
  <input #inputBX (change)="bChanged(inputAX)"/>

Then, you can check if the element has a value:

  aChanged(element) {
  if(element.value)
  }

  bChanged(element) {
  if(element.value)
  }

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

Utilize Pipe for every instance of a variable in the Controller

In my controller, I have multiple requests (POST, GET etc.) where the path includes an id parameter that needs to be a number string. I want to validate this parameter once and have it apply to all instances. Here is the current code snippet: @Get(&apo ...

NX nest application: accessing environment variables from the distribution directory

I've organized my project structure like this: https://i.sstatic.net/WRKCI.png Using nx with nest. In the app.module.ts file, I've set up the ConfigModule to read the .env file based on the NODE_ENV variable, which is then used to connect to Mo ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

A guide on incorporating Angular Material into a monolithic application in JHipster version 7.6.0

Hello everyone, I have an application built with jHipster 7.6.0 and I am trying to integrate Angular Material into it. When I run the command ng add @angular/material, I encounter this error: https://i.stack.imgur.com/J3ErS.png The issue I am facing wit ...

Steps for transferring an uploaded .CSV file to a Web service

I'm exploring the process of sending a file uploaded from the UI (angular) to a .NET web service in order for it to parse a CSV file and create a list of objects. My current understanding of the logic flow is: File upload ---> Web Service (parse ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Having difficulty mastering the redux-form component typing

I am facing an issue while trying to export my component A by utilizing redux-form for accessing the form-state, which is primarily populated by another component. During the export process, I encountered this typing error: TS2322 Type A is not assignabl ...

Image uploads are a challenge for Angular

I'm facing an issue with my Angular app while trying to upload an image to the server (node backend). Despite trying various methods found online, I have encountered the same problem consistently - the server does not receive the image. Interestingly, ...

What is the reason behind the inability of the Angular/TypeScript HTTP GET method to accept a JSON object as a parameter

EXAMPLE 1 passJSONObj(){ let name = 'user names', let email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a2a4b2a5b2bab6bebb97b3b8bab6beb9f9b2afa3">[email protected]</a>&ap ...

Passing a variable from one child component to another triggers an ExpressionChangedAfterItHasBeenCheckedError in Angular

My situation involves passing information to two children components. parent.component.html <childA [loading]="loading"> <childB (loadingChanged)="loadingChangedHandler($event)"></childB> </childA> parent.component.ts loadin ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

Using Two Unique Typeface Options in Material UI for ReactJS

Currently, in my React App, I am utilizing the Material UI library with Typescript instead of regular Javascript. I've encountered a small hurdle that I can't seem to overcome. The two typefaces I want to incorporate into my app are: Circular-S ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Switch up the item's background in the dropdown list within Kendo UI Angular

Looking for a solution to highlight text and change background color in a dropdown list based on certain conditions. I searched the official Kendo forum without success. Any guidance or suggestions on how to resolve this issue would be greatly appreciate ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...

Resolving TypeScript error when importing images statically in Next.js

In order to enhance the performance of images in my nextjs app, I am working on image optimization. However, I encountered an issue stating: Cannot find module '/images/homeBg.jpg' or its corresponding type declarations. The image is actually st ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

Using Angular 2, perform an HTTP GET request to retrieve data from a JSON file located in the assets folder

Currently, I am working on fetching data from a JSON file located in the assets folder of my application. The framework I am using is Angular Material. For this purpose, I have created an account component which consists of the following files: account.co ...

The unexpected behavior of rxjs withLatestFrom

import { of, Subject, interval } from 'rxjs'; import { tap, startWith, map, delay, publishReplay, publish, refCount, withLatestFrom, switchMap, take } from 'rxjs/operators'; const source$ = new Subject(); const res ...