Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 FormControl on valueChanges get old value

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

like image 735
karoluS Avatar asked Nov 25 '18 23:11

karoluS


Video Answer


2 Answers

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

like image 133
karoluS Avatar answered Oct 09 '22 21:10

karoluS


The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.

The best approach would be to use a validator as mentioned by @JB Nizet.

If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.

Modified Code:

export class AppComponent implements DoCheck {
  private oldValue;
  control: FormControl = new FormControl(0);

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


  }
  ngDoCheck() {
    this.oldValue = this.control.value
  }
}


StackBlitz

like image 39
Vikas Avatar answered Oct 09 '22 23:10

Vikas