Record modified fields using Angular Reactive Forms and store them in a list

Is there a method available that can identify and return the fields that have been modified within a form? I am looking to generate a list of string values for the changed fields.

I am dealing with a complex form containing approximately 30 different fields.

Manually scrolling through each field is cumbersome, especially considering some keys contain objects while others hold lists of objects.

An ideal solution would involve a function that could automatically detect and return all modified fields and objects in my form.

How can this be achieved effectively using Angular's Reactive Forms?

If possible, please provide code snippets or suggestions on how to implement validation for changed fields within my form.

StackBlitz: https://stackblitz.com/edit/angular-khiusf

Answer №1

To retrieve a list of values that have been changed, use the following method:

getDirtyValuesForForm(form: any) {
        let dirtyValues = {};

        Object.keys(form.controls)
            .forEach(key => {
                let currentControl = form.controls[key];

                if (currentControl.dirty) {
                    if (currentControl.controls)
                        dirtyValues[key] = this.getDirtyValues(currentControl);
                    else
                        dirtyValues[key] = currentControl.value;
                }
            });

        return dirtyValues;
}

You can check controls for the dirty flag by visiting https://angular.io/api/forms/FormControl.

Answer №2

By preserving the original form input, you'll be able to identify any modifications made.

To see a live demonstration, check out this example.

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

"Discovering the method to showcase a list of camera roll image file names in a React Native

When attempting to display a list of images from the user's camera roll, I utilized expo-media-library to fetch assets using MediaLibrary.getAssetsAsync(). Initially, I aimed to showcase a list of filenames as the datasource for the images. Below is m ...

Attempting to transmit the chosen value, extracted from the selection, into a function, repetitively and multiple times, within an array

I'm attempting to build a dynamic table that allows the user to select the number of rows. Each row contains two dropdown menus with options ranging from 1 to 10. Upon selecting a number from the dropdown, I want it to be passed to a function in the T ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Utilizing Angular Material's <mat-selection-list> and <mat-list-option> components seamlessly between different sections of a template

How can a <mat-list-option> declared in component sub subscribe to a <mat-selection-list> outside of component sub (for example, in component app)? (Unfortunately, I couldn't get Stackblitz to work due to my corporate's proxy restric ...

How to Retrieve Class Variables in Angular 2 Form Validator Function

I'm in the process of creating a modal-driven form with custom validation requirements. Specifically, I want to ensure that the user's password meets certain criteria (including having an uppercase letter, lowercase letter, and number). Instead o ...

Having trouble resolving TypeScript TS2322 error with Context API + useState hook in your React App?

Currently, I am working on a React Typescript project that utilizes the Context API to pass down a useState hook. export const AppContext = React.createContext(null); function App() { const [value, setValue] = React.useState(3); return ( <Ap ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Incorporating TypeScript's internal references

I am currently working on defining my own model interface that extends the Sequelize model instance. However, I am encountering difficulties in referencing the Sequelize interface within my code. Specifically, I receive an error stating "Cannot find name ...

Angular Error: "Provider's ngAfterViewInit method is not defined at callProviderLifecycles"

I encountered an error: evt = TypeError: provider.ngAfterViewInit is not a function at callProviderLifecycles while working on my Angular project. What's strange is that I do not have an ngAfterViewInit method, nor do I have the corresponding impl ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage > ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

Is there a way to access a function or variable from within the scope of $(document)?

Whenever I attempt to utilize this.calculatePrice, it does not work and I am unable to access the external variable minTraveller from within the function. numberSpin(min: number, max: number) { $(document).on('click', '.number-spinner b ...

Navigating in an Electron app using Angular

It appears that I am encountering difficulties with routing pages in my angular electron desktop application. Despite configuring the routing similar to an angular app, nothing seems to be functioning properly. I have specified router links such as "/hom ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

Setting character limits when defining string variables in TypeScript

Upon reviewing the documentation, it appears that there is no straightforward method to perform type checking for the minimum and maximum length of a string data type. However, is there a possible way to define a string data type using custom types in ord ...

Discover the latest techniques for incorporating dynamic datalist options in Angular 13 with Bootstrap 5

React 17 Tailwind CSS dynamiclist.component.html <div> <label for="{{ id }}" class="form-label">{{ label }}</label> <input class="form-control" list="{{ dynamicListOptions }}" [i ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

React 18 Fragment expressing concern about an excessive amount of offspring

Recently, I attempted to integrate Storybook into my React application, and it caused a major disruption. Despite restoring from a backup, the absence of the node_modules folder led to issues when trying 'npm install' to recover. Currently, Types ...

Angular2 - leveraging root-relative imports

Having trouble with imports in angular2/typescript? Want to use paths relative to the project root like 'app/components/calendar', but currently stuck using something like this: //app/views/order/order-view.ts import {Calendar} from '../../ ...