Search code examples
angularangular-reactive-formsangular-forms

How to check is value in form was changed from initial


I have reactive form in my Angular 7 app:

  this.userInfoForm = this.formBuilder.group({
      displayName: [this.user.displayName, [
        Validators.required,
      ]],
    })

How to check, is initial value in input was changed? Because when I use userInfoForm.dirty it return true, even if I remove 1 symbol from value and then add it back.


Solution

  • I would do like this, will use valueChanges() method of FormControl which returns an Observable that emits the latest values. You can, therefore, subscribe to valueChanges to update instance variables or perform operations.

    intialValue: any; // Define one property to store the initial value of the control
    
    this.intialValue = this.userInfoForm.get('displayName').value; // Store initial value
    
    // and then subscribe to valueChanges method of FormControl to get the latest value
    this.userInfoForm.get('displayName').valueChanges.subscribe(value => {
      console.log('Intital Value', this.intialValue)
      console.log('New Value', value);
    })
    

    Working Demo