1

I have a Reactive Form like this :

this.editform = new FormGroup({
  'username' :  new FormControl(null,[Validators.required]),  
  'password' :  new FormControl(null,[Validators.required]),  
  'full_name' :  new FormControl(null,[Validators.required]),  
  'avatar' :  new FormControl(null,[Validators.required]),   
});

In onSubmit() function, I create a variable named submitValue and pass form value to this varibale:

   onSubmit() {
    const submitValue = this.editform.value
    submitValue.username = 'Jon';
    console.log(this.editform.value.username) // Output : 'Jon'  [The value of editform also changed]
  }

But whenever I change submitValue value, the editForm value also changed. I only want to get form value from edit form and handle it in submitValue. Is there anyway that I can do it.

2
  • Can you share your html code as well? Commented May 6, 2020 at 7:16
  • Are you trying some like const submitValue={...this.editform.value} (a copy of the object)? Commented May 6, 2020 at 8:10

3 Answers 3

1

It is a reference issue, you can deepCopy the reference using any method like

const submitValue = Object.assign({},this. editform.value);

or

const submitValue = JSON.parse(JSON.stringify(this. editform.value));

or using lodash cloneDeep function

Sign up to request clarification or add additional context in comments.

Comments

1
const submitValue = Object.assign({},this. editform.value);

**Explanation:**
  Whenever we use an assignment operator to assign an object to another variable, it uses pass by reference and maintains it.

Example:

var a = {name: 'abc', age: 12,};
   var b = a;
   b.age = 13;
   console.log(a,b) // you can see a.age is also having 13

Now if you use below code

var b = Object.assign({}, a);
   b.age = 13
   console.log(a) // This will not change a due to Object.assign()

**Object.assign()**

   Properties in the target object are overwritten by properties in the sources if they have the same key.

Comments

0

Sure. You can create an intermediate submitValue object, copying the form's value and overwriting parts of it:

const submitValue = { ...this.editform.value, username = 'Jon' };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.