6

In Angular 2+, is it possible to reset value of an input to its previous value programmatically?

I have 'Select' dropdown, whereupon selecting a value I need to reset its value to the previous one, if certain validation fails.

How can I achieve the same using ngModel (Template form) and formControl (Reactive Form)? (Just need to know if its possible by both the approaches).

I have figured out that if we place the ngModelChange event before the ngModel in the select tag in the template, the in the ngModelChange event we get value of ngModel prior to the change. Reference: https://github.com/angular/angular/issues/11234

But I think this approach is not concise and might be confusing at times.

1 Answer 1

6

Yes, it is possible using Reactive forms approach and with rxjs operator pairwise.

Subscribe to formControl valueChanges in your component with rxjs operators pairwise and startWith

Sample code :

this.myForm.controls['control1'].valueChanges
  .pipe(startWith(1), pairwise()).subscribe(
    ([prevValue, selectedValue]) => {
      console.log(prevValue); // previous value
      console.log(selectedValue); // new value
    }
 );
} 

You can also check the working DEMO

Note : I am using startWith because, pairwise will emit values when it has two values (prev and current). So add default value 1 (value of default option) in startWith.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response, but the functionality described here is tagged as a bug: github.com/angular/angular/issues/13129. So I doubt this will be a right approach
@AbhinandanKhilari True, Another way is to do with rxjs operators. Check the updated answer and demo as well.
Thanks, I think this will work, will try out soon. Just out of curiosity, is it possible to reset value with ngModel using template form appoach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.