Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous value of reactive form?

I have form:

this.filterForm = this.fb.group({
      type: [null, [Validators.required]]});

I listen changes:

this.filterForm.controls["type"].valueChanges.subscribe(
      selectedValue => {

});

In code above I get selectedValue of element, how to get previous value to make comparing like:

if (old("type") !== selectedValue) {
   // Call user method
}

I tried to do this with two others fields in form:

Observable.merge(this.filterForm.controls["classNumber"].valueChanges, this.filterForm.controls["classSuffix"].valueChanges).subscribe(response => {
        if (response[0] !== this.filterForm.value.classNumber && this.filterForm.controls["classSuffix"]) { // Call method }
    });
like image 803
OPV Avatar asked Dec 01 '18 10:12

OPV


3 Answers

I used this solution to get previous value from reactive form. Pairwise puts the current and previous values together in one array and emits that.

like image 72
johannesMatevosyan Avatar answered Sep 18 '22 12:09

johannesMatevosyan


You can use this method in order to achieve your concern:

Had created a demo for your reference and check the stackblitz console

this.filterForm
   .controls["type"]
   .valueChanges
   .subscribe(selectedValue => {
       // New value of Type;
       console.log('New Value: ', selectedValue);

       // Old value of Type; Avoid using this.filterForm.get('type').value
       // This will give you the current/latest value.                 
       console.log('Old Value: ', this.filterForm.value['type']);   
});
like image 30
KShewengger Avatar answered Sep 19 '22 12:09

KShewengger


why not use a variable oldValue?

oldValue:any;
this.filterForm.controls["type"].valueChanges.subscribe(
      selectedValue => {
           console.log(selectedValue,oldValue);
           oldValue=selectedValue; //<--give value to oldValue;
});

Anyway, in a select valuesChanges happens only if you choose a new value (not if drop down is shown and select the value yet selected)

like image 27
Eliseo Avatar answered Sep 18 '22 12:09

Eliseo