简体   繁体   中英

Angular 2 copy reactive form without reference

I have a reactive form that when submitted, needs to round some of the values submitted, without effecting how the values look on the page.

To do this, I created a method that creates a new form and rounds the values, then returns for the actual form submission:

     mapFormValues(): FormGroup {
        const newForm: FormGroup = this.myOriginalForm;

        const fieldsToRound = ['field1', 'field2', 'field3'];

        fieldsToRound.forEach((field: string) => {
            if (newForm.get(field).value >= 1000) {
                const formField = newForm.get(field).value / 1000;
                newForm.get(field).setValue(formField);
            }
        });

        return newForm;
    }

The problem is that, since my newForm is just a reference to my original form, it still changes the original form values on the page itself.

How can I create a copy of the form that I can transform values on, without changing my original form?

I looked at Clone Object without reference javascript but it seems I can't do this with FormGroups.

As this worked, i'll post as an answer. Basically what you need to do is get the values from the form to process it. To do this the FormGroup has a method called getRawValue(), which returns the data of a fromGroup this data is not reference therefore it will not affect your formGroup.

This data is a json object which can be modified freely. You can use this object to update or create another FormGroup

// My form for clarity
   this.myForm = this.formBuilder.group({
      customerName: '',
      someNumber: 0
    })

//

// Gets the values from the form
let temp = this.myForm.getRawValue();

// Modify at your will
temp.customerName = 'Peter';

// Save to original form
this.myForm.setValue(temp);
console.log(this.myForm.getRawValue(), 'Original Form')

// Or modify as you want and create another form with the data
delete temp.someNumber;
let myForm2 = this.formBuilder.group(temp)

// Form created with the values from the original form minus the someNumber attribute that i deleted
console.log(myForm2.getRawValue(), 'Form created with the object')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM