I have a button that, when clicked, triggers another component. Before doing so it logs information about the event.
I am new to LWC. I couldn’t find the solution in LWC reference guide.
<template for:each={animeData} for:item="anime">
<div key={anime._id} class="Anime-Item">
<div class="Title">
<h1>{anime.title}</h1>
<p class="Ranking">Id: {anime._id}</p>
<p class="Ranking">Ranking: {anime.ranking}</p>
<p class="Genres">Genres: {anime.genres}</p>
<p class="Episodes">Episodes: {anime.episodes}</p>
<p class="Has-Episode">Has Episode: {anime.hasEpisode}</p>
<p class="Has-Ranking">Has Ranking: {anime.hasRanking}</p>
<p class="Status">Status: {anime.status}</p>
<p class="Type">Type: {anime.type}</p>
<a class="Anime-Link" href={anime.link}>More Details</a>
<button class="Book-Anime" id={anime._id} onclick={handleBookNow}>Book Now!</button>
</div>
<img class="Anime-Image" src={anime.image} alt="Anime Image">
</div>
</template>
handleBookNow(event) {
const animeId = event.target.id;
console.log('Book Now button clicked for Anime ID:', animeId);
this.bookNow(event);
}
bookNow(event) {
const animeId = event.target.id; // Consistent access to animeId
console.log('Book Now action initiated for Anime ID:', animeId);
this.isBook = true;
this.isError = false;
}
connectedCallback() {
this.getData();
}
2
Answers
It started working after few hours, Its really weird, I guess salesforce lwc issue. For the same code
You should use data attribute. I haven’t run the code below, but it should work. If not, click on the link and do as in the example.
HTML:
JS:
Here you can find example
In case if you need provide value from one LWC component to another LWC component you can use Custom event.
firstComponent.html
firstComponent.js
secondComponent.html
secondComponent.js
Documentation about Custom Event