我有一个反应式表单,提交时需要将一些提交的值四舍五入,而不影响值在页面上的外观。
为此,我创建了一个方法,该方法创建一个新表单并将其四舍五入,然后返回实际表单提交:
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;
}
问题在于,由于我的newForm
只是对原始表单的引用,因此它仍会更改页面本身上的原始表单值。
如何在不更改原始表单的情况下创建可以转换值的表单的副本?
我看着 Clone Object without reference javascript,但似乎无法使用FormGroups做到这一点。
答案 0 :(得分:0)
由于此方法有效,我将发布答案。
基本上,您需要做的是从表单中获取值以对其进行处理。为此,FormGroup
有一个名为getRawValue()的方法,该方法返回该数据未被引用的fromGroup的数据,因此不会影响您的formGroup。
此数据是可以自由修改的json对象。您可以使用此对象来更新或创建另一个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')