angular - 将表单值添加到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 中处理它。反正有没有我能做到的。
解决方案
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.
推荐阅读
- python - Python split() 复制
- c# - 实例化数组中的特定对象时如何触发事件?
- python - 在python中附加文本文件
- java - 如何使用 jdbc 从表行中获取数据?
- docusignapi - DocuSign,发送 2 个文档,signhere documentid 被忽略
- oracle - 如何在以下 SQL 查询中找到错误?
- api-platform.com - API 平台验证错误与 ORM 异常
- javascript - HTML中的背景不会根据可变数字而改变
- python - 无法使用列表满足 maxheap 属性
- azure - 如何在 Teams 中获取访问令牌?