I have more than 15 fields in the form, If user open the form in Edit mode, and the value of the form is not updated, then it shows message value is not changed on click of update button. Otherwise if the form value is changed then it shows message "Data updated".
I don't need updated value, i just need to check the value is updated or not on button click.
Below is my code which i tried but this is not working on update button click.
HTML
<div>
<form id="editfrm" [formGroup]="Editunit">
<div>
<input type="text" formControlName="name" />
</div>
<div>
<input type="text" formControlName="code" />
</div>
</form>
</div>
<footer>
<button class="btn btn-secondary" type="reset" (click)="update(Editunit.value)">Edit</button>
</footer>
//Component.ts file
update(Editunit?) {
this.Editunit.valueChanges.subscribe((data) => {
if(data is changed){
alert("Data updated");
}else{
alert("form not updated");
}
return;
});
}
you can subscribe to valueChanges of the form and use pairwise to check if there was a change else if you "change" an input with the same value Angular give you changed
changed:boolean=false;
this.form.valueChanges.pipe(
takeWhile(()=>!this.changed),
startWith(this.form.value),
pairwise()
).subscribe(([old,value])=>{
let change=false;
Object.keys(old).forEach(k=>{
change=change || old[k]!=value[k]
})
this.changed=change;
})
Or simply get the olds values in a variable, and check the values
this.oldValues={...this.form.value} //after create the form
isChanged()
{
let change=false;
Object.keys(this.oldValues).forEach(k=>{
change=change || this.oldValues[k]!=this.form.value[k]
})
return change
}
See stackblitz
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.