I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function.

button.tsx

  {((this.test1) || this.selectedExistingId) &&
                      (<button class="pdp-button primary"
                          onClick={this.saveSearch}>{this.langSave}</button>)
                    }

In sentence.tsx, I want to be able to detect when this button is clicked and display a specific div if the user has clicked it.

sentence.tsx

           {onClick={saveSearch} &&  (<div class="styles-before-arrow">{this.langConfirmSearchSaved}</div>)}

Answer №1

Here are a few options for you to consider:

  1. If you want to add a click event listener for the button component in sentence.tsx, you can do so by following these steps. Please note that it might be a bit more challenging if you are dealing with elements enclosed in Shadow DOM:
addButtonLister(): void {
  document.querySelector('.pdp-button')
          .addEventListener('click'), (e) => {
      // add your logic here.
  });
}
  1. Another option is to use EventEmitter (check out ). In your button.tsx file, you can include the following:
@Event({eventName: 'button-event'}) customEvent: EventEmitter;

Then, you can implement something like this in your button's onClick function:


emitEvent() {
  customEvent.emit('clicked');
}

render () {
  return <button onClick={this.emitEvent}>{this.langSave}</button>
}

After that, in your sentence.tsx file, you can add an event listener for your button component as shown below:

// assuming your button component's tag is <button-component>
document.querySelector('button-component')
        .addEventListener('button-event', (e) => {
    // your logic here.
});
  1. If suitable for your specific use case, you can also utilize Stencil Store. However, be mindful that it might be excessive depending on your requirements - check out this link for more details:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch up the Position of a Frame with jQuery

I'm attempting to cycle through an array of URLs in order to designate them as locations for a frame. The current setup I have can be found on this fiddle: var l = ['0', '1', '2', '3', '4', '5&ap ...

How can I ensure the button remains disabled until all inputs are completed in Redux form?

I am currently studying a react-redux form example that you can find at the following link: In this example, the submit button is enabled if the user fills in at least one input field. I am curious to know if there is a way to enable the button only when ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

The ng-bootstrap typeahead is encountering an error: TypeError - Object(...) is not functioning correctly

Hey there! I'm trying to integrate the Angular Bootstrap typeahead component in my Angular 5 application by following the linkToTypeahead. However, I'm encountering some errors along the way. Here's what I'm seeing: ERROR TypeError: Ob ...

Typescript interface requiring both properties or none at all

I possess key-value pairs that must always be presented together in a set. Essentially, if I have one key with its value A:B, then there should also be another key with its value C:D. It is permissible for the object to contain neither pair as well. (An ex ...

Exchange selection choices among harvested selected boxes

In my project, I am working on swapping all the options between two select boxes. The specific scenario I am dealing with involves recording details of phone calls. These calls can either be inbound or outbound. For outbound calls, I have a 'caller&ap ...

What strategies can I use to prevent making multiple API calls inside setInterval when initializing a new connection in a socket?

I am currently working on implementing a socket system where users can request a function with an ID, and after receiving the ID, I send requests to an API every second and emit the response back to the user. Issue: Every time a new user requests the same ...

The value binding for input elements in Angular 4 remains static and does not reflect changes in the UI

Struggling with binding input to a value in angular 4? Take for example [value]="inputFrom". Sometimes it updates when I change inputFrom, other times it doesn't. How can I ensure the input always changes whenever inputFrom changes, not sporadically? ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

cookies cannot be obtained from ExecutionContext

I've been trying to obtain a cookie while working with the nestjs and graphql technologies. However, I encountered an issue when it came to validating the cookies by implementing graphql on the module and creating a UseGuard. It was suggested that I ...

Tips for transferring information from a form to your email address

I am trying to find a way to automatically send form data to my email without the user having to open their inbox. I attempted to use the "mailto" function but it didn't work as desired, still opening the email box. Here is the script I tried: functio ...

Responsive Grey Tiles for Google Maps v3

I've successfully implemented Google Maps V3 in my project, but I'm encountering an issue with grey tiles appearing on the map. I attempted to fix this problem by triggering a resize event using the following code snippet: google.maps.event.trig ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

Can spreading be used for destructuring?

These were the initial props I attempted to pass to a component: const allprops = { mainprops:{mainprops}, // object pageid:{pageId}, // variable setpageid:{setPageId}, // state function makerefresh:{makeRefresh} // state function } <Na ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

angularjs determining the appropriate time to utilize a directive

I have been delving into JavaScript and AngularJS for approximately a month now, but I still find myself unsure of when to use directives. For example: I am looking to display appointments in a table with the date as the table header. I envision having bu ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and I’m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...