0

How do I add a click event to a pill within a pill-container?

I tried to add the click event to the items array but it didn't trigger an event, I really don't know how else I can get to the pill.

import { LightningElement } from 'lwc';

export default class Basic extends LightningElement {
    items = [
        {
            type: 'avatar',
            label: 'Avatar Pill 1',
            class:'prod',
            onclick: 'onclickmethod'
        },
    ];


    onclickmethod(event){
        console.log('run')
    } 
}

<template>
    <lightning-pill-container
        items={items}
        onitemremove={handleItemRemove}>
    </lightning-pill-container>
</template>

Demo

P.S: I know about the remove event, this not what I'm looking for, I want the user to click on the pill and not on the 'x' mark.

1 Answer 1

3

Use Lightning-pill instead

HTML:

<template>
    <h1>Selected Item: {infoText}</h1>
    <template for:each={items} for:item="item" for:index="index">
        <lightning-pill label={item.label} key={item.key} data-index={index} onclick={handleClick}></lightning-pill>
    </template>
</template>

JS

import { LightningElement, track } from 'lwc';

export default class Basic extends LightningElement {
    @track infoText;
    items = [
        {
            type: 'avatar',
            label: 'Avatar Pill 1',
            class:'prod',
            key: 1
        },
        {
            type: 'avatar',
            label: 'Avatar Pill 2',
            class:'prod',
            key: 2
        }
    ];


    handleClick(event) {
        const index = event.target.dataset.index;
        let selectedItem = this.items[index];
        this.infoText = selectedItem.label;
    }
}
1
  • Thanks again Anmol Kumar
    – Json
    Mar 20, 2020 at 10:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .