Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 Rxjs distinctUntilChanged operator

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!

like image 708
ciolas2 Avatar asked Apr 12 '26 21:04

ciolas2


1 Answers

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);
    });
  }
like image 73
AliF50 Avatar answered Apr 15 '26 11:04

AliF50