简体   繁体   中英

Angular2 - click event: get ID of clicked element

I have an overview of charts (primeng) and now I need to know if it is possible to get the ID from a chart when its clicked.

FYI I have a contextmenu which contains "open in new tab" and I need the ID from the chart the contextmenu opened on.

Rightclick -> getID from chart -> use ID to open new Tab with only that chart being displayed.

I've seen some stuff like event.target.attributes.id /event.currenttarget, but that's js, right? I am using Typescript.

So the question is actually that simple: How would I be able to do this?

I am a newbie to everything related to programming, I acutally started a few weeks ago, so please be patient as I might not be able to understand everything as quick as others would.

Edit:

MenuItems for context menu:

this.ctitems = [
    {
        label: 'Öffnen(neuer Tab)',
        icon: 'fa-plus',
        command: (onClick) => {this.function()}                
    },
    {
        label: 'Öffnen(dieser Tab)',
        icon: 'fa-hand-o-down'

    }
]; 

function to get id

function() { event.target.getID <- problem }

As soon as I have the ID I want to push an item specified by the ID into an array of items displayed in a TabMenu. But thats future. Now I just need to get the ID.

html:

<p-chart height="100" width="100" class="ui-g-2 " type="line" id="linechart" [data]="ntwdata"></p-chart>
<p-contextMenu id="cm" [model]="ctitems"></p-contextMenu>

You're not passing the event variable to your function, so you can't use it.

Define your command like this, then it should work:

this.ctitems = [
    {
        label: 'Öffnen(neuer Tab)',
        icon: 'fa-plus',
        command: (event) => onClick(event)                
    },
    {
        label: 'Öffnen(dieser Tab)',
        icon: 'fa-hand-o-down'

    }
];

[...]

onClick(event) {
    let target = event.target || event.srcElement || event.currentTarget;
    let idAttr = target.attributes.id;
    let id = idAttr.nodeValue;
    console.log(id);
}

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