4

I'm designing a calendar-like form. This form has seven fields: a date, and three pair of start time / end time. I want to update the model according to the user actions:

  • if the user prepone/postpone the start time, I want to prepone/postpone the end time aswell;
  • if the user prepone the end time, I want to prepone the start time aswell;
  • if the user postpone the end time, I want to do nothing more.

In order to understand if the user preponed or postponed a time, I was thinking of comparing the time before and after the change. While I'm able to retrieve the value after the change, I still can't find a way to retrieve the value before the change.

  • The form isn't an @Input, so I can't listen to NgOnChanges.
  • I can listen to the (change) event of every <input>, but the event is fired after the model is changed, and the $event object only carry the new value (as far as I know).
  • I can listen to the (ngModelChange) of every <input>, but the event only carry the old new value, with no information about the form control which changed.

So, is there a way to know which field changed, from which value to what value?

Andrea
  • 675
  • 1
  • 13
  • 34
  • For the old value, you can try the suggestion given in [this answer](https://stackoverflow.com/a/41544123/1009922). By the way, the event of `ngModelChange` gives the new value. You could get the field with the help of template reference variables, but I don't know if having to set a variable for each field suites your needs. – ConnorsFan Feb 02 '18 at 15:04

1 Answers1

0

Use Angular reactive form. You can add all controls to a form group and then listen to valueChanges event of each of the controls. valueChanges will provide new value. As for the old value you can save the values in variables when the page loads and you set up this form. When valueChanges triggers you can compare old value with new value. For example.

    this.calendarForm = new FormGroup({
            startTime: new FormControl('<current value>')
        }),
    });     
    this.currentStartTime = this.calendarForm.get('startTime').value;//existing value
    this.calendarForm.get('startTime').valueChanges.(newValue => {
        if ((newValue !== this.currentStartTime)
            //do something
        }
    });
Atif Majeed
  • 1,021
  • 17
  • 14