[英]Angular Reactive forms : how to get just changed values
Im building a reactive forms using angular 6, this form contain 3 attributes (name,age,phone) and i would to get just the changed values not all form values.我使用 angular 6 构建了一个反应式表单,该表单包含 3 个属性(姓名、年龄、电话),我只想获取更改后的值而不是所有表单值。
this.refClientForm = this.formBuilder.group({
name: [],
phone: [],
age: []
});
for the form listener :对于表单侦听器:
this.refClientForm.valueChanges.subscribe(values => console.log(values))
but i got always all form values.但我总是得到所有形式的价值。
You can check all controls for dirty-flag. 您可以检查所有控件的脏标志。 See https://angular.io/api/forms/FormControl
参见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;
}
There is a simple way to check if any control is dirty in the reactive form. 有一种简单的方法可以检查是否有任何控件在反应形式中脏了。
getUpdatedValues() {
const updatedFormValues = {};
this.form['_forEachChild']((control, name) => {
if (control.dirty) {
this.updatedFormValues[name] = control.value;
}
});
console.log(this.updatedFormValues);
Better answer found here:更好的答案在这里找到:
Angular 2 Reactive Forms only get the value from the changed control Angular 2 Reactive Forms 仅从更改的控件中获取值
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);
}
);
使用 pairwise() 运算符和 startWith(this.refClientForm.value) 运算符,然后表单 valueChanges 将在第一次尝试时发出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.