skip to Main Content

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


  1. Chosen as BEST ANSWER

    It started working after few hours, Its really weird, I guess salesforce lwc issue. For the same code


  2. 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:

    <button class="Book-Anime" data-id={anime._id} onclick={handleBookNow}>Book Now!</button>
    

    JS:

    handleBookNow(event) {
        const animeId = event.target.dataset.id;
        console.log('Book Now button clicked for Anime ID:', animeId);
        this.bookNow(event);
    }
    

    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

    <button class="Book-Anime" data-id={anime._id} onclick={handleBookNow}>Book Now!</button>
    

    firstComponent.js

    handleBookNow(event) {
        const animeId = event.target.dataset.id;
        this.dispatchEvent(new CustomEvent('book', {detail: {animeId: animeId}}));
    }
    

    secondComponent.html

    <c-first-component onbook={handleBook}></c-first-component>
    

    secondComponent.js

    handleBook(event) {
        let animeId = event.detail.animeId;
        console.log(animeId);
    }
    

    Documentation about Custom Event

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search