I have a problem with my code and distinctUntilChanged operator.
This is my code:
ngAfterViewInit() {
fromEvent(this.headlineInput.nativeElement, 'blur').pipe(
takeUntil(this.unsubscribe$),
map((evt: any) => evt.target.value),
distinctUntilChanged()
).subscribe((text: string) => {
this.onInputValueChanges(text);
});
}
In this code, I would like to run this.onInputValueChanges(text) method on blur, but only once something has changed in headline input. If not, it should not run this method in subscribe.
I thought I can use distinctUntilChanged, but it seems to not working. It runs anytime I make a blur from my headline input. Am I doing something wrong? Can someone point me out what is wrong in this code? Thanks!
If you want to be lazy, you can just check the object value being different than the previous emission.
ngAfterViewInit() {
fromEvent(this.headlineInput.nativeElement, 'blur').pipe(
takeUntil(this.unsubscribe$),
map((evt: any) => evt.target.value),
// don't run if the stringified version of the object is the same.
distinctUntilChanged((pre: any, curr: any) => JSON.stringify(pre) === JSON.stringify(curr)),
).subscribe((text: string) => {
this.onInputValueChanges(text);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With