Tips for sending just the updated section of the form

I am working with a form group where I map the values from the form to an object type in order to make a request to edit the item.

This is my form structure:

  public companyForm = new FormGroup(
    {
      generalInfo: new FormGroup({
        name: new FormControl('', [Validators.required, Validators.maxLength(this.maxLength)]),
        active: new FormControl(false)
      }),
      address: new FormGroup({
        street: new FormControl('', [Validators.required, Validators.maxLength(this.maxLength)]),
        streetNumber: new FormControl('', [Validators.required]),
        postalCode: new FormControl('', [Validators.required]),
        city: new FormControl('', [Validators.required]),
        country: new FormControl('', [Validators.required])
      })
   })

Here is the CompanyEdit object structure:

      name: formValue.generalInfo.name,
      active: formValue.generalInfo.active,
      address: {
        street: formValue.address.street,
        city: formValue.address.city,
        streetNumber: formValue.address.streetNumber,
        postalCode: formValue.address.postalCode
      },
      country: formValue.address.country

The field names and nesting structure do not align. When editing, I need to send only the changed controls on the form. Is there a recommended way to identify the dirty controls and map them to my object type?

Answer №1

If you want to see if there are any dirty values in a formGroup, you can easily check for them.

I came across a solution to a similar issue on stackoverflow here. I have included the code snippet below for your reference.

  function findDirtyValues(form: any) {
        let dirtyValues = {};

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

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

        return dirtyValues;
}

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

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...

TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations. To achieve this, I have been experimenting with the data ...

I am able to view the node-express server response, but unfortunately I am unable to effectively utilize it within my Angular2 promise

https://i.stack.imgur.com/d3Kqu.jpghttps://i.stack.imgur.com/XMtPr.jpgAfter receiving the object from the server response, I can view it in the network tab of Google Chrome Dev Tools. module.exports = (req, res) => { var obj = { name: "Thabo", ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

Struggling to get the bindings to work in my Angular 2 single-page application template project

I have recently started using the latest SPA template within Visual Studio 2017: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp.net-core-with-javascriptservices/ The template project is functioning properly. ...

Issue with Bootstrap Angular dropdown menu malfunctioning within ChildRoute

Recently, I have been working on integrating admin bootstrap html with Angular. As part of this integration, I added CSS and JS files in angular.json as shown below: "styles": [ "src/styles.css", "src/assets/goo ...

Tips for dismissing loader in Ionic 4

I'm struggling to programmatically dismiss the loader. I've developed two separate methods - one for displaying the loader and another for dismissing it. These methods are called accordingly when needed. async showLoader() { this.loader = a ...

Optimal approach for securely managing API credentials within Angular 2+ applications

I am facing a dilemma with my app that uses Google OAuth for authentication. I have stored my Google client id and secret in the environment.ts file of my Angular project. However, I do not want this sensitive information to be exposed if I publish my code ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Best Practices for Updating UI State in Client Components Using NextJS and Server Actions

My goal is to create a page using nextjs 14 that functions as a stock scanner. This page will retrieve data from an external API using default parameters, while also offering users the ability to customize parameters and re-run the scan to display the resu ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Leverage TypeScript to enforce the value of a property based on the keys of another property

The issue at hand is illustrated in the following example: type ExampleType = { properties: { [x: string]: number; }; defaultProperty: string; }; const invalidExample: ExampleType = { properties: { foo: 123, }, defaultProperty: "n ...

Form appears outside the modal window

I am facing an issue with my modal where the form inside is displaying outside of the modal itself. Despite trying to adjust the CSS display settings and switching to react-bootstrap from regular bootstrap, the problem persists. I am uncertain about what s ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...

Implement a conditional block in my form validation process

Greetings, I have hit a roadblock with this issue for the past few days Here's the problem: I have an input field where I need to display a message based on certain conditions. One condition specifies that if it is a multiline text, use a textarea; o ...