this.element.nativeElement is wrong this


#1

Hi all,

Im trying to get the x & y coords of the button in my Ionic View page.
This is my HTML:

<button #data class="drag-button" draggable="true" (click)="show()" data-id="{{ btn.id }}" [style.background-color]="btn.kleur">
      {{ btn.artikelnummer }}
</button>

But now when I click on the button it send its to my show function in home.ts
That contains the following code:

show(){
        console.log(this.element.nativeElement);
        console.log('left  ' + event.srcElement.nativeElement.offsetLeft);
        console.log('top  ' + event.srcElement.nativeElement.offsetTop);
    }

At top of my Home.ts I got:

import { Directive, Component, ElementRef, ViewChild } from '@angular/core';

And in my constructor I got:

constructor(private http: Http, private element:ElementRef, public navCtrl: NavController) {

But the problem now is that If I click on the button.
the nativeElement is returning the following:

But it has to be in the first console.log:

<button #data class="drag-button" draggable="true" (click)="show()" data-id="{{ btn.id }}" [style.background-color]="btn.kleur">
      {{ btn.artikelnummer }}
</button>

And beside of that I’m not receiving any offsetLeft / Top coords.

I hope some one can help me out.

Thanks in advance.


#2

I solved it with another method.

I install the jQuery library for Ionic and did it like this:

home.html

<button class="drag-button" draggable="true" (click)="show($event)" data-id="btn{{ btn.id }}" [style.background-color]="btn.kleur">
     {{ btn.artikelnummer }}
</button>

home.ts
At top I included

import * as $ from 'jquery'

And my function

show(event){

     let value = event.srcElement['attributes']['id']['value'];

     var pos = $('#'+value).offset();
        
     console.log(pos.left);
     console.log(pos.top);
 }

#3

Just use ngDraggable
Why to use jQuery when you have so simple clean language