#Signal with Rxjs using input ngModel

16 messages · Page 1 of 1 (latest)

worldly lava
#

I am learning about signal. I created one input text with ngModel, ngModelChanges with signal. My question is why toObservable and toSignal interop methos is not called when input value changed?

This is input with searchQuery() signal used as inside ngModel like below.

  <input type="text" [ngModel]="searchQuery()" (ngModelChanges)="searchQuery.set($any($event.target).value)" />

component code is look a like this below.

  export class SignalRxjsPractice {
  searchService = inject(SearchService);
  searchQuery = signal('');
  search$: Observable<any[]> = toObservable(this.searchQuery).pipe(
    debounceTime(250),
    filter((q: string) => q.length > 0),
    switchMap((queryString: string) => this.searchService.search(queryString))
  );
  results = toSignal(this.search$, { initialValue: [''] });
}

My question is when I am typing in input box, why nothing is going to show up for results signal and event service search method is not called. Thanks.

Here is full stackblitz link https://stackblitz.com/edit/stackblitz-starters-x1wzpv?file=src%2Fmain.ts,signal-practices%2Fsignal-rxjs-practice.component.ts

StackBlitz

An angular-cli project based on @angular/animations, @angular/common, @angular/compiler, @angular/core, @angular/forms, @angular/platform-browser, @angular/platform-browser-dynamic, @angular/router, core-js, rxjs, tslib and zone.js

reef helm
#

That's a typo 😭

#

ngModelChanges => ngModelChange

#

Mind it returns the value directly so: (ngModelChange)="searchQuery.set($event)"

worldly lava
#

Ohh! Super thanks. It is really that typo. Now it is working.

#

@reef helm Would you like to suggest any other better way of doing this? Or this is better already to do? Thanks.

reef helm
#

I was thinking about trying this way.
The 'better way' will depends on how you deal with data loading/error handling.

worldly lava
reef helm
#

About results = toSignal(this.search$, { initialValue: [''] });.
I'm still wondering about using directly search$ with the async pipe.
How far do you want to use signals?

worldly lava
#

I want to use signal for this component only.

#

I have read about that when using signal as compared to rxjs observable inside component template then, ChangeDetection cycle will run only for that two components. Not for whole child tree.

reef helm
#

Ok i haven't explored Signals that far i confess.

worldly lava
#

Okay. One last question, How do we decide to use signal over rxjs?. Because, rxjs operators are very easy to use as compared to signal.

reef helm
#

For the same usecase you use here: for streams and events, rxjs will always shine.

zenith timber