Reputation: 65
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.
Upvotes: 1
Views: 2945
Reputation: 364
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.
Upvotes: 2
Reputation: 41581
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
Upvotes: 1
Reputation: 14699
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' };
Upvotes: 0