POV
POV

Reputation: 12015

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 }
    });

Upvotes: 15

Views: 21913

Answers (3)

KShewengger
KShewengger

Reputation: 8269

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']);   
});

Upvotes: 28

johannesMatevosyan
johannesMatevosyan

Reputation: 2228

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.

Upvotes: 8

Eliseo
Eliseo

Reputation: 58019

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)

Upvotes: 2

Related Questions