admin管理员组

文章数量:1279176

I find plenty of resources on how to bind Angular HostListeners:

@HostListener('document:click', ['$event'])
handleClick(event: Event) {
     // etc
}

but how would I use RxJs instead, to stream it?

documentClickedStream = Observable.fromEvent(/* how to bind this? */)

Not sure how to bind to create a "click anywhere" stream using the decorator pattern suggested in the Angular docs.

I find plenty of resources on how to bind Angular HostListeners:

@HostListener('document:click', ['$event'])
handleClick(event: Event) {
     // etc
}

but how would I use RxJs instead, to stream it?

documentClickedStream = Observable.fromEvent(/* how to bind this? */)

Not sure how to bind to create a "click anywhere" stream using the decorator pattern suggested in the Angular docs.

Share Improve this question edited Jul 20, 2018 at 17:32 FlavorScape asked Jul 20, 2018 at 17:18 FlavorScapeFlavorScape 14.3k12 gold badges78 silver badges123 bronze badges 3
  • 1 what are you actually trying to acplish? you want some other ponent in your application to get notified through ngrx whenever click on this ponent occurs? or? – tlt Commented Jul 20, 2018 at 17:22
  • Can you point to decorator documentation link please? – Wand Maker Commented Jul 20, 2018 at 17:25
  • oops, updated question, I really meant just how to handle a click anywhere on Host element with RxJs, not ngrx. I typed too fast. – FlavorScape Commented Jul 20, 2018 at 17:25
Add a ment  | 

4 Answers 4

Reset to default 5

I guess the easy way is to just use an intermediary subject:

  @HostListener('document:click', ['$event'])
  onKeyUp(e:Event) {
      this.clickStream$.next(e);
  }

then sub to it like normal

  this.clickStream$
      .asObservable()
      .pipe(
          // some operators...
      )
      .subscribe();

Here is my working example. First you need to import this lines into your ponent


import { fromEvent } from 'rxjs/internal/observable/fromEvent';

then put this code into your ponent constructor or into ngOnInit

   fromEvent(document, 'click').subscribe(event => {
      console.log(event);
    })

Use template ref to get ref of button

It will work since we are targeting document.

@ViewChild('btn') btn:ElementRef;
documentClickedStream = Observable.fromEvent(window['document'],'click');

Working example:https://stackblitz./edit/rxjs-window

You can subscribe to RxJs events using below given code as well, add below given code to ngOnInit event:

this.subscribe(fromEvent(document, 'visibilitychange'), (e: Event) => {
    console.log('visibilitychange');
    this.getVisibilitychange(true);
});

本文标签: javascriptHow do I stream HostListener events using RxJsStack Overflow