Difference Between Angular's @HostBinding( 'window:resize' ) And Rxjs' fromEvent( window, 'resize' )

Viewed 792

I am just wondering what advantages there are using the one instead of the other.

@HostListener( 'window:resize' )
doSomething(): void {
    // ...throttle with setTimeout and clearTimeout maybe...
}

and

fromEvent( window, 'resize' ).pipe(
    // ... debounceTime, takeUntil etc.
).subscribe( () => {
    doSomething();
})

Is it really just a question of context (e.g. easier handling the stream of events by using pipe() ), or is the observable more «mordern», or doesn't it matter at all?

Thanks!

1 Answers

The fromEvent will give you more flexibility with execution and pipe lining as well as the possibility to bind outside of the NgZone context.

The @Hostlistener has an advantage where you don't have to manually trigger the change detection after an event is fired. You do need to that with Observables when your component uses the OnPush change detection strategy, which is the advised (but not default) strategy. There are other cases where you need to do this when using fromEvent, but those are very much edge cases.

Another advantage of HostListener is that you don't need to unsubscribe when the component destroys, as this is done automatically.

So mainly, it's all about preference and context.

ad There are third party libraries (mine) out there which extend the HostListener and template event binding stuff with debounce and other cool features.

Related