简体   繁体   中英

How to get an ID, on click, from a button in Ionic 2?

I have a button <button (click)="navToPage2($event)" #button block id="test">Click here</button>

when I click on it, i want to get the id attribute:

navToPage2(event) {
    console.log(event.target.attributes);
}

The issue i'm having is that if I click on it I get NamedNodeMap {0: class, length: 1} with no 'id'

But, if i click right on the edge I get NamedNodeMap {0: block, 1: id, 2: class, length: 3} with the id

The issue is because of the way this button rendered:

<button block="" id="test" class="button button-default button-block">
    <span class="button-inner">Click here</span><ion-button-effect></ion-button-effect>    
</button>

The span has some padding and if i click outside the span , I get the id

here is a sample https://codepen.io/patrioticcow/pen/XKzdXv?editors=1010 .Make sure to open the browser console to see the result

Any ideas?

You're already defining the template variable #button , so you can actually pass it to get the right element id.

<button (click)="navToPage2($event, button)" #button block="" id="test" class="button button-default button-block">
    <span class="button-inner">Click here</span><ion-button-effect></ion-button-effect>    
</button>

And in your method:

navToPage2(event, button) {
    console.log(button.id);
}

Working Plunker example

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