2

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Edon
  • 1,116
  • 2
  • 22
  • 47
  • have you tried ``let myVar = form.getRawValue()``? to extract the json of the form and using said variable to round and send, this should not affect the original form – victor dencowski Dec 03 '18 at 20:59
  • Thanks for the response @victordencowski , this worked! Since my form is small this solution worked great, I had no idea getRawValue existed. I wonder if there is another way to accomplish this. Just as a note, I had to ```return this.fb.group(newForm);``` since ```this.myOriginalForm.getRawValue();``` is not of type FormGroup. Feel free to post this as answer! – Edon Dec 03 '18 at 21:12

1 Answers1

4

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')
victor dencowski
  • 1,398
  • 2
  • 12
  • 12