Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Reset input value to previous value

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.

like image 790
Abhinandan Khilari Avatar asked Jan 27 '19 16:01

Abhinandan Khilari


People also ask

How to reset the values in Angular?

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.

How to reset Form in Angular material?

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.

How do you make input field empty after submit in angular?

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.


1 Answers

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.

like image 56
Amit Chigadani Avatar answered Sep 16 '22 14:09

Amit Chigadani