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.
import { ViewChild } from "@angular/core"; ViewChild allows you to set a reference variable to your input, using that you can clear the value of input. After clearing the value of input using the reference variable, the selected file will be reset.
Resetting a form in template-driven approach: In template driven approach, we need to import NgForm from '@angular/forms' and we use [(ngModel)] directive for two way data-binding and we should also import FormsModule from '@angular/forms' in app. module. ts file.
If you are using [(ngModel)] directive to control your form input fields, then you can clear it by setting an empty string ( ' ' ) to the ngModel control property.
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
.
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