0

I am creating an array of pills and would like to add a data-* attribute to each item. But unfortunately I get a syntax error.

I tried changing the field name 'data-id' to 'dataId' but still wasn't able to query the field using event.target.dataset.dataId.

What is the right syntax for this?

Playground

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {

    @track items = [

    ];
    handleClick(event){
        let obj ={
            label: 'test', 
            data-Id: 'my data id' <---- This is where I get syntax error
        }           
        this.items.splice(this.items.length,0,obj)  //adding new items to array
    }  
    copyPillToForm(event){
        console.dir(event.target.dataset.data-Id)

    }
}
3
  • Your playground is completely broken. Please make the code a MVR (Minimum Viable Reproduction). Also, do not post your code as a screenshot, but as plain text using the {} button.
    – sfdcfox
    Commented Mar 20, 2020 at 18:37
  • You're right, edited my question and playground.
    – Json
    Commented Mar 20, 2020 at 18:42
  • Is there a reason you don't want to add the data-* directly to the pill in the markup? Commented Mar 20, 2020 at 19:07

1 Answer 1

3

When using iteration you nee to set up the Key for the iterator

Then the usage of data attribute is as follows

Assume you are using data-id the you are accessing that attribute in js code

event.target.dataset.id

if the data attribute is like data-key then you will access it by event.target.dataset.key

Similarly I have update the code in the playground.

html file:

<template>
<lightning-button style="" label="Add" title="Non-primary action" onclick={handleClick} class="testclass"></lightning-button>
<template for:each={items} for:item="item" for:index="index">
    <lightning-pill label={item.label} key={item.key} data-id={item.dataid} data-index={index} onremove={handleRemoveOnly}></lightning-pill>
</template>

Js file :

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {

  count = 0;
  @track items = [
  ];
  handleClick(event){
    let obj ={
        key: this.count++,
        label: 'test',
        dataid:'id' + this.count
    };           
    this.items.splice(this.items.length,0,obj)  //adding new items to array
  }  
  handleRemoveOnly (event){
    console.dir(event.target.dataset.id)
  }
}

You must log in to answer this question.

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