Angular 7 FormControl on valueChanges get old value

karoluS picture karoluS · Nov 26, 2018 · Viewed 15.7k times · Source

I got a formControl passed in @Input parameter that is bounded to input of number type that maximum value should be 10. When user types number that is bigger it should not change input value.

What is the way to either prevent event propagation or get old value and set it again?

I tried many other solutions from stack and github, but nothing solves my problem.

 valuecontrol: FormControl = new FormControl(0);

  constructor(){
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
      if(newValue >= 10){
        // set previous value
        const oldValue = this.control.value;
        console.log("old value = ", oldValue)
        this.control.patchValue(oldValue);
      }
    })
  }.

DEMO: https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts

Answer

karoluS picture karoluS · Mar 17, 2020

After a year more of experience I think I found an optimal solution. To solve this problem the best way probably would be to use pairwise rxjs operator

Thank to that you are able to get the previous value of the stream.

The provided snippet does not solve the original problem as it would require few additional steps but It solves the original question on "How to get the old value?".

Here comes the code:

control: FormControl = new FormControl(0);

  constructor(){
    this.control.valueChanges.pipe(
      distinctUntilChanged(),
      pairwise() // gets a pair of old and new value
    ).subscribe(([oldValue, newValue])=>{
      console.log(oldValue, newValue)
      if(newValue >= 10){
        // set previous value
        this.control.patchValue(oldValue);
      }
    })
  }

Living code: https://stackblitz.com/edit/angular-tfrstg