Angular Reactive Forms: Enhancing User Interaction

Currently, I am delving into reactive forms and encountering difficulty in pinpointing the form control that has been updated or changed from the UI. When using the valueChanges() method, it retrieves the entire form instead of the specific form control that was altered.

Despite my attempts with the valueChanges() method, I have yet to achieve the targeted outcome I expected.

Answer №1

To optimize your form control subscriptions, you can subscribe to specific controls instead of the entire form like this:

this.form.get('userName').valueChanges(value=> console.log('name change',value))

You can dynamically manage form control subscriptions by doing the following:

this.form = fb.group({
  name: [],
  age: [],
  address: [],
});

Object.keys(this.form.controls).forEach(key  => {
  this.form.get(key).valueChanges.subscribe(value =>{
    console.log(`control ${key} has changed =>` ,value)
  })
});

Check out a demo on stackblitz 🚀🚀

Answer №2

Utilize the valueChanges pipe along with the pairwise operator to access both the previous and current values. By comparing these values, you can identify which controls have changed.

constructor(private fb: FormBuilder) {
    this.form = fb.group({
      name: [],
      age: [],
      address: [],
    });

    this.form.valueChanges.
       pipe(debounceTime(2000), startWith(null), pairwise()).  
       subscribe(([prev, next]) => {
        if (prev === null) { // 👈 run only first time 
          console.log(this.getValue(next))
        } else { // 🚨 compare values
          const result = {};
          const keys = Object.keys(next);

          keys.forEach(key => {
            if (prev[key] !== next[key]) {
              result[key] = next[key]
            }
          });
          console.log(result); // 🔵 the value that has changed 
        }
      })
  }

  // 👇👇 
  // for the first time all form controls are null 
  // so this method gets the value of objects that have a value 
  getValue(obj) {
    return Object.keys(obj).reduce((prev: any, key) => {
      if (obj[key]) {
        prev[key] = obj[key];
      };
      return prev;
    }, {})
  } 

Check out the stackblitz demo 🔥🔥

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

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Navigating back to the top of a webpage within an Angular iframe on Safari desktop

One of my challenges involves an Angular 5 application which is embedded into an Iframe on various sites to create an application form. Whenever a user clicks 'Next' to move to the next section of the form, I require the page to scroll back to th ...

Creating a line chart in Angular 2 using d3.js, pulling data from a server URL instead of locally stored data

Struggling with creating a d3 v4 linechart using dummy data from a server in Angular 2. I found some guidance here: https://bl.ocks.org/mbostock/3883245. I'm new to both Angular2 and d3, any help would be greatly appreciated. Someone managed to do it ...

Can you explain the function and purpose of the <template> element in Angular 2?

Within the angular2 control file, specifically on line 91, there is a unique tag called <template>. What purpose does this tag serve? ...

Using TypeScript's interfaces to push items

Can anyone provide some guidance on working with interfaces in typescript? I currently have the following 3 interfaces: export interface HomeMenu { [name: string]: MenuItem; } export interface MenuItem { title: string; route: string; hom ...

A guide to strictly defining the subclass type of object values in TypeScript

How do I enforce strict subclass typing for object values in the SHAPE_PARAMS definition? When using type assertion like <CircleParameter>, missing properties are not caught by linting. Is there a way to define subclass types strictly? const Shapes ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

Angular is facing a challenge in locating the main parent based on its class interface

After reading the angular documentation here, I implemented a Parent class like this: export abstract class Parent {} In the AlexComponent, I set this component as the Parent for its children with the following code: providers: [{ provide: Parent, useExis ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Invoking the asynchronous function Subscription within the ngOnInit lifecycle hook of a component

retrieving data from my service without waiting for it to complete. This is the Component responsible for fetching data for my grid. The issue lies in this part: this.store.loadRequestHistory(this.id). When hovering over store, no data is displayed from i ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

It is not possible to utilize a JavaScript function once the script has been loaded through

I am attempting to programmatically load a local JavaScript file - PapaParse library, and then utilize one of its functions: $.getScript("./Content/Scripts/papaparse.js", function () { console.log("Papaparse loaded successfully"); Papa.parse(file, ...

Utilizing TypeScript to access global variables and external libraries

Currently, I am in the process of converting traditional JavaScript files into TypeScript for use in client-side deployments within SharePoint. Within SharePoint, there are global variables and libraries that we rely on without needing to explicitly load t ...

When I hover over the content, the image displayed in the tooltip is causing a flickering effect

Dealing with Angular in this situation, my goal is to have an image or video displayed inside a tooltip when hovering over specific content. However, there seems to be a flickering effect before the image renders, making the transition less smooth compared ...

How come Angular8's routerLinkActive is applying the active class to both the Home link and other links in the navigation bar simultaneously?

Currently, I am facing an issue with routing in my project where the home tab remains active even when I click on other tabs. I have tried adding routerLinkActiveOption as a solution, but it doesn't seem to be working for me. <ul class="nav nav-ta ...

Automatically Populate Data Table with Email Addresses

After logging into the application, I am using the angular-datatables package from https://www.npmjs.com/package/angular-datatables. The search bar in the datatable auto fills with the email id upon login as shown in the image Data Table. However, I need ...

TypeScript - Determining the type of an array with multiple data types

When dealing with an array of union, checking the typeof value can be done this way: //case 1 function something1(a1: Array<number | string | boolean>) { for (const v of a1) if (typeof v === "number") v; //v is number ...

I've noticed that the list item vanishes unexpectedly when utilizing Primeng drag-and-drop feature

Whenever I try to drag an item from one list to another in the Primeng picklist, the item disappears until it is dropped. <p-dialog [(visible)]="showMarker" (onHide)="hideDialogChild()" [contentStyle]="{'overflow':'visible'}" h ...