简体   繁体   中英

How to listen to all mobile events in angular

I'm trying to listen to all mobile events like touch, swipe etc. I've added eventListener on document level.:

document.addEventListener('tap', trackTouchActivity, false);
document.addEventListener('swipe', trackTouchActivity, false);


function trackTouchActivity(event) {
    // any activity
}

This works only on the first page of the angular app but doesn't work on other pages/controller of the app.

I also tried adding the code in $rootScope

app.run(function($rootScope){
  document.addEventListener('swipe', trackTouchActivity, false);
  document.addEventListener('tap', trackTouchActivity, false);

  function trackTouchActivity(event) {
     $rootScope.$apply(function(){
        // any activity
        // some variable = true
        });
    }
});

I'm new to angular and may be I'm doing something wrong. How do I achieve the functionality of event listening throughout the app?

To listen to touch(start) on Component X:

@Component({
host: {
'(document:touchstart)': 'onClick($event)',
 },
})

class SomeComponent() {
constructor(private _eref: ElementRef) { }


onClick(event) {
if (!this._eref.nativeElement.contains(event.target)) 
 doSomething();
  }
}

For the other events I suggest using NgTouch , you will be able to listen to any other mobile behavior with this package.

Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM