Do touch events work in ionic like this? Get screenX with the Angular framwork

sebay Source

Is the ionic framework able to use touch events like in js?

Just like this:

   var t = htmlElement.touches[0];
   var output = t.screenX + " , " + t.screenY;  

   var t = htmlElement.touches[0];
    var output = t.screenX + " , " + t.screenY; 

I need the t.screenX and the t.screenY value in ionic

thanks for your help 👌



answered 1 month ago theriddle2 #1

It is certainly possible, you can achieve this like so:

var element = document.getElementsByClassName('htmlelement');
element[0].addEventListener('click', (e: any) => {

However usually a better wat to declare event handlers in ionic is to define it in HTML:

 <button (touchstart)="foo($event);">Element 1</button> 
 <button (touchend)="foo($event);">Element 2</button>

And then declare a function in component that handles these events

foo (event) {
     // Function logic here

answered 1 month ago Sergey Rudenko #2

So what's wrong accessing screenX, screenY from just normal angular (click) binding?

if you bind event using $ in the template:

<div (click)="getEvent($event)"></div>

In your getEvent method you can access original DOM event object that contains screenX,Y etc

getEvent(event) {
      "Your screen X: "+ event.screenX +" and Y : "+event.screenY

(click) event is handled by hammer.js in Ionic 3, and it should work for both touch and mouse input.

for touch you can also use (tap) binding. Then screenX, screenY should be accessible inside event.srcEvent path

And if you still want to do the binding to low level touch/mouse event on your own ideally you need to leverage "renderer" to ensure your code stays "decoupled" from dom:

// check your Angular version to know which Renderer you need to import:
import { Renderer2 } from "@angular/core";

// inject it:
    private renderer: Renderer2

// use ViewChild to bind to DOM element:
@ViewChild('mainSVG') mainSVG: ElementRef;

// do binding in life cycle hook for instance:
ionViewDidLoad() {
    this.renderer.listen(this.mainSVG.nativeElement, 'touchstart', this.startInputEvent)

This looks more complex and for simple projects I guess can be ignored, but in general it is better to let Angular touch dom and deal with it in its own way.

comments powered by Disqus