我有Angular Reactive Form验证。
为hiddenComposedField
调用setter的正确方法是什么?
ngOnInit() {
this.myForm = this.formBuilder.group({
'field1': ['', [Validators.required]],
'field2': ['', [Validators.required]],
'hiddenComposedField': [''],
});
this.myForm.get('field1').valueChanges.subscribe((val) => {
this.setHiddenComposedField();
});
this.myForm.get('field2').valueChanges.subscribe((val) => {
this.setHiddenComposedField();
});
}
setHiddenComposedField() {
let field1 = this.myForm.get('field1').value;
let field2 = this.myForm.get('field2').value;
// This doesn't work, but I want something like it:
this.myForm.set('hiddenComposedField',field1 + ' ' + field2); // :(
}
<form [formGroup]="myForm">
<input formControlName="field1">
<input formControlName="field2">
<!-- NB: hiddenComposedField is not exposed to the user; -->
<!-- it is only on the submitted form model. -->
<button type="submit">Submit</button>
</form>
答案 0 :(得分:4)
这样的事情应该有效,这样你首先获得Control,然后设置它的值。
this.myForm.get('hiddenComposedField').setValue(field1 + ' ' + field2);
答案 1 :(得分:0)
使用字符串插值的方式略有不同
setHIddenField(){
const field1 = this.myForm.get('field1').value;
const field2 = this.myForm.get('field2').value;
const separator= ' --- ';
let result = `${field1} ${separator} ${field2}`;
this.myForm.get('hiddenComposedField').setValue(result);
}
这是StackBlitz链接。
答案 2 :(得分:0)
这个问题的终极解决方案是订阅表单控件的valueState。
import pandas as pd
path = "data.csv"
df = pd.read_csv(path)
import { combineLatest } from 'rxjs';
每当您更改表单中的值时,c 字段都会自动更新。
这是解决此类问题最合适的方法。