0

Attempting to simulate a mouse click on one button, by clicking on another button. The goal is to reuse the behavior of a single custom button throughout the page. Why is the dispatchEvent not working?

How can a click on <c-custom-button> be simulated?

parentApp.html

<template>
    <div>
        <c-custom-button
            label="New">
        </c-custom-button>
    </div>
    <div>
        <lightning-button
            label="Call New"
            onclick={simulateClick}>
        </lightning-button>
    </div>
</template>

parentApp.js

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    cButtonElement;

    simulateClick() {
        this.cButtonElement = this.template.querySelector('c-custom-button');
        let clickEvent = new CustomEvent('click');
        this.cButtonElement.dispatchEvent(clickEvent);
    }

}

customButton.html

<template>
    <lightning-button
        label={label}
        icon-name="utility:new"
        onclick={handleClick}>
    </lightning-button>
</template>

customButton.js

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    @api label;

    handleClick() {
        this.label = 'CLICKED!'
    }
}
jvol
  • 26
  • 5

1 Answers1

0

Thanks to Nathan Shulman for helping with this.

Add call to child method in parentApp.js

    simulateClick() {
        this.cButtonElement = this.template.querySelector('c-custom-button');
        this.cButtonElement.handleClick();
    }

Add @api decorator to method in customButton.js

    @api handleClick() {         
        this.label = 'CLICKED!'
    }
jvol
  • 26
  • 5