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.
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
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
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 将在第一次尝试时发出
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.