2

I am trying to to add this button with function deleteData to delete a specific row on the screen for the UI. So if I have 3 emails listed, it would render 3 on screen. But if I were to click the delete button for any of them on their specified row, it would delete that whole row from the array/UI. I am currently stuck and not able to figure it out and am asking what a possible solution would look like.

HTML:

<template>
     <template for:each={emails} for:item='email'>
          <div key={email.index}>
               <div class="slds-grid slds-wrap">
                    <div class="slds-col slds-size_1-of-4">
                         <lightning-input label="Email" title="Email" data-index={index} value={email.emails}></lightning-input>
                    </div>
                    <div class="slds-col slds-size_1-of-4">
                         <lightning-button type="button" variant="base" label="Delete" icon-name="utility:delete" onclick={deleteData}</lightning-button>
                    </div>
               </div>
          </div>
     </template>
     <lightning-button type="button" variant="base" label="Add Email" icon-name="utility:add" onclick={clickedAddEmail}></lightning-button>
</template>

JS:

userEmails= [{index:0,eamils:''}]

clickedAddEmail(){
     this.userEmails=[...this.userEmails, {index:this.userEmails.length+1,emails:''}];

}

1 Answer 1

4

There's a lot of ways to do this in JS, but one of the easiest is to just splice it out:

deleteData(event) {
  const index = this.userEmails.findIndex(user => user.index === event.target.dataset.index)
  // at start index, delete 1 element
  this.userEmails.splice(index, 1)
  // Triggers render cycle
  this.userEmails = [...this.userEmails]
}

Make sure you add the property to your button, too:

<lightning-button data-index={email.index} type="button" variant="base" label="Delete" icon-name="utility:delete" onclick={deleteData}</lightning-button>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.