Angular 7 FormControl on valueChanges get old value
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
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