I have a reactive form with 3 controls in it, I want to detect changes of the form. I have created a value change method of the form and subscribed to it but. Right now every time any of it's control value is changing the event is emitting.
If user has added any value to ant of this 3 controls and trying to exit the page, then I want to promt a modal that there is unsaved changes in the form.
How can I be able to check the emitted value on change of the form is different than it's initial value?
public createGroupForm : FormGroup;
ngOnInit() {
this.createGroupForm = this._formBuilder.group({
groupName: new FormControl("", [Validators.required]),
groupPrivacy: new FormControl(null, [Validators.required]),
groupTagline: new FormControl('')
});
this.onCreateGroupFormValueChange();
}
onCreateGroupFormValueChange(){
this.createGroupForm.valueChanges.subscribe(value => {
console.log(value);
//emitting every time if any control value is changed
});
}
you must each time your subscribe is emitted check the form value with initial value and use hasChange when ever you want
public createGroupForm : FormGroup;
hasChange: boolean = false;
ngOnInit() {
this.createGroupForm = this._formBuilder.group({
groupName: new FormControl("", [Validators.required]),
groupPrivacy: new FormControl(null, [Validators.required]),
groupTagline: new FormControl('')
});
this.onCreateGroupFormValueChange();
}
onCreateGroupFormValueChange(){
const initialValue = this.createGroupForm.value
this.createGroupForm.valueChanges.subscribe(value => {
this.hasChange = Object.keys(initialValue).some(key => this.form.value[key] !=
initialValue[key])
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With