1

I'm trying to dynamically set the onclick function of lightning web component button but it's not working. I've tried both "click" and "onclick"

JS:

const navButton = this.template.querySelector('.nav-button');
navButton.label = "Done";
navButton.addEventListener('onclick',this.handleShowMenu);

HTML:

<lightning-button 
   class="slds-m-left_small nav-button"
   label="Next"
   variant="brand"
   onclick={handleNext}>
</lightning-button>
3
  • Hi. Can you explain why you want to dynamically set it? You are already setting it using the onclick property binding in your template...
    – Phil W
    Dec 16, 2019 at 19:05
  • So I have a form so when the user gets to the last page I change the button label to "Done" and the onclick needs to change from "handleNext" to "handleFinished"
    – 626
    Dec 16, 2019 at 19:09
  • just one remark to your code sample: if you will use addEventListener() the corresponding string would be 'click' not 'onclick' Feb 21, 2020 at 14:32

1 Answer 1

4

You don't have to manually apply onclick event listener to <lightning-button>. But you can handle this or any other event in the container component. Just define the function handleNext:

<!--container.html-->
<template>
   <lightning-button class="slds-m-left_small nav-button"
                     label="Next"
                     variant="brand"
                     onclick={handleNext}>
   </lightning-button>
</template>
/* container.js */
export default class Container extends LightningElement {

   handleNext(event) {
       // handle onclick event
   }

}
3
  • I have a form so when the user gets to the last page I change the button label to "Done" and the onclick needs to change from "handleNext" to "handleFinished"
    – 626
    Dec 16, 2019 at 19:10
  • 1
    You can design any logic just within the onclick handler, keeping and manipulating the state in properties. Dec 16, 2019 at 19:12
  • Yeah, I was planning to do that. Thanks for the help!
    – 626
    Dec 16, 2019 at 19:14

You must log in to answer this question.

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