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>
  • 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 '19 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 '19 at 19:09
  • just one remark to your code sample: if you will use addEventListener() the corresponding string would be 'click' not 'onclick' – Christian Menzinger Feb 21 at 14:32
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
   }

}
| improve this answer | |
  • 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 '19 at 19:10
  • 1
    You can design any logic just within the onclick handler, keeping and manipulating the state in properties. – Oleh Berehovskyi Dec 16 '19 at 19:12
  • Yeah, I was planning to do that. Thanks for the help! – 626 Dec 16 '19 at 19:14

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.