我将使用角度6来构建反应式表单,该表单包含3个属性(名称,年龄,电话),我将只获得更改后的值,而不是所有表单值。
this.refClientForm = this.formBuilder.group({
name: [],
phone: [],
age: []
});
对于表单侦听器:
this.refClientForm.valueChanges.subscribe(values => console.log(values))
但是我总是得到所有表单值。
答案 0 :(得分:4)
您可以检查所有控件的脏标志。参见https://angular.io/api/forms/FormControl
getDirtyValues(form: any) {
let dirtyValues = {};
Object.keys(form.controls)
.forEach(key => {
let currentControl = form.controls[key];
if (currentControl.dirty) {
if (currentControl.controls)
dirtyValues[key] = this.getDirtyValues(currentControl);
else
dirtyValues[key] = currentControl.value;
}
});
return dirtyValues;
}
答案 1 :(得分:1)
有一种简单的方法可以检查是否有任何控件处于反应形式中。
getUpdatedValues() {
const updatedFormValues = {};
this.form['_forEachChild']((control, name) => {
if (control.dirty) {
this.updatedFormValues[name] = control.value;
}
});
console.log(this.updatedFormValues);
答案 2 :(得分:0)
在这里找到更好的答案:
Angular 2 Reactive Forms only get the value from the changed control
this.imagSub = this.imagingForm.valueChanges.pipe(
pairwise(),
map(([oldState, newState]) => {
let changes = {};
for (const key in newState) {
if (oldState[key] !== newState[key] &&
oldState[key] !== undefined) {
changes[key] = newState[key];
}
}
return changes;
}),
filter(changes => Object.keys(changes).length !== 0 && !this.imagingForm.invalid)
).subscribe(
value => {
console.log("Form has changed:", value);
}
);