The Angular manual for Practical Observables gives an example of using debounce in type-ahead:
const typeahead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => e.target.value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);
Meanwhile, another part of the manual recommends using Renderer2.listen() for DOM interaction. Also, this Medium post has some pretty emphatic advice to not manipulate the DOM directly.
I've read this related Q&A for 'click' events, which could apply to 'input' events.
What's vexing me is that I'm looking for consistent philosophy of design throughout the Angular manual (and it has plenty of that). This feels inconsistent.
Also, the two approaches are not exactly the same.
In the case of Renderer2.listen()
an unlisten()
function is returned to prevent memory leaks. Not so with fromEvent
. I suspect that fromEvent
isn't leaking, but I don't know and more importantly, if it is, why would the manual recommend this method?
Finally, I accept that there may be absolutely no difference between these two methods. Surely, then, the manual would bias towards using Renderer2
in that case.
Which leaves me asking what about the type ahead suggestion is better than the listen()
method?
Update
I appreciate the answers and the comment and together, they clarified some things for me. Basically, coding in the event model world saddles the developer with a lot of complexities. It seems that rxjs
is in response to that world, an easier/cleaner way to consume events. I also appreciate the Answer that essentially says: "RTFM", so I went and did that, too.
If I decided I had to use Renderer2.listen()
, and yet I also want to take advantage of Observables' simpler programming model, I'd have to convert listen()
call into an Observable. I believe that looks like this:
new Observable(obs => renderer.listen(el.nativeElement, 'input', e => obs.next(e)))
Which, in the end, I imagine the fromEvent
operator does under the covers.
It would seem the advantage of the fromEvent
code is also that I don't have to inject a Renderer2
into my component, I need only locate the ElementRef
for the target DOM object. The point being, I can have an Observable either way, one of which is much simpler to describe and code.