Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Reactive form value is changed from initial

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
    });
}
like image 649
RAHUL KUNDU Avatar asked Jan 24 '23 13:01

RAHUL KUNDU


1 Answers

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])
    });
}
like image 124
mehranmb78 Avatar answered Jan 31 '23 09:01

mehranmb78