Can we access the key attribute when handling an event from a foreach template

// TEMPLATE    

<template for:each={itemList} for:item="item">
  <li key={item} onclick={handleItemClicked}>{item}</li>
</template>

// JS

itemList = ['A','B','C'];
selectedItem = '';

handleItemClicked(event) {
  this.selectedItem = event.target.key;
}

Is there a way to get to the key value ?

Answer

You can set a data attribute on the element and read that.

Your template will look something like this:

<template for:each={itemList} for:item="item">
  <li key={item} data-item={item} onclick={handleItemClicked}>{item}</li>
</template>

And then your function will look like this:

handleItemClicked(event) {
        this.selectedItem = event.target.dataset.item;
    }

Also there are a few things wrong with your code other than this.

onclick={handlItemClicked} should be onclick={handleItemClicked}

itemList = {'A','B','C'}; is not valid javascript. Assuming you want an array, it should be itemList = ['A','B','C'];

Attribution
Source : Link , Question Author : Jovabe , Answer Author : John Towers

Leave a Comment