首页 > 解决方案 > 将表单值添加到Angular中的变量

问题描述

我有一个这样的反应形式:

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]),   
});

在 onSubmit() 函数中,我创建了一个名为 submitValue 的变量并将表单值传递给该变量:

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

但是每当我更改 submitValue 值时,editForm 值也会更改。我只想从编辑表单中获取表单值并在 submitValue 中处理它。反正有没有我能做到的。

标签: angulartypescriptangular-reactive-forms

解决方案


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.

例子:

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

现在,如果您使用以下代码

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.

推荐阅读