Sunday, March 26, 2023

Custom Events in Lightning Web Components : Pass data from child component to parent component in LWC

In order to communicate from child component to parent component in LWC, we use custom events. Custom events helps in passing data from child components to parent component in containment hierarchy.

If you want to refer on how same thing can be achieved in Aura Components then refer below article:

Component Events: Way to Communicate Between Components in Containment Hierarchy


Lightning component can create and dispatch events in a component’s JavaScript class. To create an event, use the CustomEvent() constructor. To dispatch an event, call the EventTarget.dispatchEvent() method.

The CustomEvent() constructor needs one required parameter, which is a string indicating what event has been performed. You can define ant string as event name. While defining event name, follw below recommendation based on DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

Steps involved in implementing custom events

1. Create custom event in child component and dispatch that event.

    const newEvent = new CustomEvent("search");
    this.dispatchEvent(newEvent);

2. Handle the event in parent component.

When you declare the child component in parent component, then use "on" event handler to execute logic whenever the event is fired. Suppose you event name which is dispateched from child component is "search", event handler name will be "onsearch".

<c-sk-child-cmp onsearch={capturedEvent}></c-sk-child-cmp>
capturedEvent(event) {
    console.log("**recieved event-->" + event);
}

Custom events to inform what action is performed in child component

If you want to inform parent component about what has been clicked or operation performed in child component, then you can simply define custom event as mentioned below:

<template>
    <lightning-button label="Edit" onclick={editAction}></lightning-button>
    <lightning-button label="New" onclick={deleteAction}></lightning-button>
</template>

    editAction() {
const newEvent = new CustomEvent("edit");
        this.dispatchEvent(newEvent);
    }

    deleteAction() {
const newEvent = new CustomEvent("delete");
        this.dispatchEvent(newEvent);
    }


Custom events to pass data to parent component

If you want to pass data to parent component, then set a detail property in the CustomEvent constructor. 

You can pass any record id  or any data from child component in detail property.

@track selectedRecordId;

handleResponse(event) {
const answerEvent = new CustomEvent("search", { detail: this.selectedRecordId});
this.dispatchEvent(answerEvent);
}

Parent component can access detail property in order to read data passed from child component

 capturedEvent(event) {
    console.log("**recieved event detail-->" + event.detail);
 }


Note: There is no restriction on data type of detail property but is is recommended to pass only primitive data. JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detail property. Copying the data to a new object ensures that you’re sending only the data you want, and that the receiver can’t mutate your data.

Lets try to understand custom events through simple example:

We will create a child component "skChildCmp" which will contain few buttons. Once user will click on one of the button, child component will pass resource URL based on button click to parent component and parent component will display that URL.

Below is snapshot for parent component:


Now when user clicks on SFDCSTUFF BLOGS button, URL for that button will be appearing on parent component.


If user clicks on TRAILHEAD button, then parent will display URL for that.


Below is complete code snippet:



Hope this will help!!

11 comments:

  1. Too good Blog with Excellent Stuff sir.
    Keey Writing More Information With us.
    Thank You....!

    Interested guys Please Check it Out,
    Salesforce Training in Hyderabad

    ReplyDelete
  2. I think everyone should read your blog who want to learn more about synopsis mapc ignou

    ReplyDelete
  3. Glass replacement is a necessary service that car owners may require at some point in their vehicle's lifespan. The glass components of a car serve several purposes, including protecting passengers from the elements, providing visibility while driving, and contributing to the car's structural integrity. In this blog post, we will discuss the importance of glass replacement, how to identify when replacement is necessary, and what to expect during the replacement process.
    Importance of Glass Replacement
    The glass components of a car are crucial to a driver's safety on the road. Any damage to the glass can compromise the integrity of the vehicle and put passengers at risk. Windshields, side windows, and rear windows are all essential components that need to be in good condition for safe driving. In addition, damaged glass can lead to visibility issues, making it challenging to drive safely in different weather conditions.
    Identifying the Need for Glass Replacement
    There are several signs that indicate the need for glass replacement. Cracks or chips on the windshield or other glass components can impair visibility and compromise the structural integrity of the vehicle. Additionally, broken or shattered glass can be hazardous and need to be replaced immediately. If you notice any damage to your car's glass, it is best to seek professional help as soon as possible to avoid further damage or injury.
    The Glass Replacement Process
    The glass replacement process is typically straightforward and can be completed in a few hours. A professional glass replacement technician will assess the damage and determine if the glass component can be repaired or if it needs to be replaced entirely. If the glass needs to be replaced, the technician will remove the damaged glass and install a new one. They will also ensure that the glass fits properly and

    ReplyDelete

  4. Glass replacement is a necessary service that car owners may require at some point in their vehicle's lifespan. The glass components of a car serve several purposes, including protecting passengers from the elements, providing visibility while driving, and contributing to the car's structural integrity. In this blog post, we will discuss the importance of glass replacement, how to identify when replacement is necessary, and what to expect during the replacement process.
    Importance of Glass Replacement
    The glass components of a car are crucial to a driver's safety on the road. Any damage to the glass can compromise the integrity of the vehicle and put passengers at risk. Windshields, side windows, and rear windows are all essential components that need to be in good condition for safe driving. In addition, damaged glass can lead to visibility issues, making it challenging to drive safely in different weather conditions.
    Identifying the Need for Glass Replacement
    There are several signs that indicate the need for glass replacement. Cracks or chips on the windshield or other glass components can impair visibility and compromise the structural integrity of the vehicle. Additionally, broken or shattered glass can be hazardous and need to be replaced immediately. If you notice any damage to your car's glass, it is best to seek professional help as soon as possible to avoid further damage or injury.
    The Glass Replacement Process
    The glass replacement process is typically straightforward and can be completed in a few hours. A professional glass replacement technician will assess the damage and determine if the glass component can be repaired or if it needs to be replaced entirely. If the glass needs to be replaced, the technician will remove the damaged glass and install a new one. They will also ensure that the glass fits properly and seals correctly to prevent any leaks.

    ReplyDelete
  5. vCar glass repair is something that most car owners will need at some point in their vehicle's life. Windshields are an essential component of a car and are crucial to a driver's safety on the road. In this blog post, we will discuss why car glass repair is important, how to identify damage, and what to do if you need repairs.
    Importance of Car Glass Repair
    The windshield of a car serves several purposes, including protecting drivers and passengers from the elements and providing structural support to the vehicle. A damaged windshield can compromise the safety of the vehicle and its occupants. In the event of an accident, a damaged windshield may not be able to provide adequate protection, leading to more severe injuries.
    Identifying Damage
    There are several ways to identify damage to a windshield. Chips and cracks are the most common types of damage. Chips are small dents on the windshield caused by rocks or other debris. They are usually small and do not require the windshield to be replaced. Cracks, on the other hand, are more severe and can spread across the windshield if not repaired in a timely manner. Scratches are also a common type of damage, but they are usually minor and do not require repair.
    What to Do if You Need Repairs
    If you notice any damage to your windshield, it is essential to take action immediately. Even small chips and cracks can quickly become larger and more dangerous. In some cases, small chips can be repaired with a resin injection. However, more significant damage may require a full windshield replacement. It is always best to seek professional help when it comes to car glass repair.
    Final Thoughts
    Car glass repair is a vital aspect of vehicle maintenance that should not be ignored. Any damage to the windshield can compromise the safety of the vehicle and its occupants. If you notice any chips, cracks, or scratches on your windshield, seek professional help immediately. By taking care of your windshield, you can ensure safe driving and prevent more significant damages in the long run.

    ReplyDelete
  6. Car Battery service are essential for powering the electrical components of your car, from starting the engine to running the lights, radio, and air conditioning. However, car batteries don't last forever, and eventually, you'll need to replace them to keep your car running smoothly. In this blog post, we'll explore the importance of battery replacement services and what you can expect from the process.
    Why Replace Your Car Battery?
    Car batteries typically last between three and five years, depending on the make and model of your car and your driving habits. When your battery starts to wear out, you may notice signs like dimming lights, slow engine cranking, or difficulty starting the car. Failing to replace a worn-out battery can cause further damage to your car's electrical system or leave you stranded with a dead battery.
    Here are some reasons why you should consider replacing your car battery:
    Improved Performance: A new battery will provide more consistent and reliable power to your car's electrical system, which can improve your car's overall performance.
    Increased Reliability: A failing battery can cause your car to stall or fail to start altogether, leaving you stranded or causing a dangerous situation on the road. A new battery will help ensure that your car is reliable and safe to drive.
    Long-Term Savings: A new battery will last longer than a worn-out one, which means that you'll save money in the long run by avoiding frequent replacements.
    What to Expect from Battery Replacement Services
    Battery replacement services are straightforward and typically take less than an hour to complete. Here are the steps involved in the process:
    Inspection: A technician will inspect your car's battery to determine if it needs to be replaced or if there are other issues that need to be addressed.
    Removal: The technician will remove the old battery and safely dispose of it.
    Installation: The technician will install a new battery that is compatible with your car's make and model and meets the necessary safety and performance standards.
    Testing: The technician will test the new battery to ensure that it's functioning properly and providing the necessary power to your car's electrical components.

    ReplyDelete

  7. When it comes to website designing, bookmarking is a feature that allows users to save and easily access their favourite pages or content on a website. Here are some tips on creating content that is conducive to bookmarking:
    Make content easily scannable: Users are more likely to bookmark content that is easy to read and understand. Use headings, subheadings, and bullet points to make your content easy to scan.
    Use clear and concise language: Use language that is easy to understand and free of jargon. This will make your content more accessible and increase the likelihood of it being bookmarked.
    Provide valuable information: Users are more likely to bookmark content that provides value. Make sure your content is informative and provides practical solutions to problems.
    Use visuals: Use images, infographics, and videos to break up your content and make it more engaging. Visuals can also make your content more memorable and increase the likelihood of it being bookmarked.
    Make it easy to share: Include social media sharing buttons on your website so that users can easily share your content with others. This can increase visibility and encourage bookmarking.
    Offer downloadable content: Consider offering downloadable content such as ebooks, guides, or whitepapers. This can provide added value to users and increase the likelihood of your content being bookmarked.


    ReplyDelete
  8. <I lost my job few months back and there was no way to get income for my family, things was so tough and I couldn’t get anything for my children, not until a met a recommendation on a page writing how Mr Bernie Wilfred helped a lady in getting a huge amount of profit every 6 working days on trading with his management on the cryptocurrency Market, to be honest I never believe it but I took the risk to take a loan of $2000. and I contacted him unbelievable and I was so happy I earn $22,500 in 6 working days, the most joy is that I can now take care of my family I don’t know how to appreciate your good work Mr. Bernie Doran God will continue to bless you for being a life saver I have no way to appreciate you than to tell people about your good services.
For a perfect investment and good strategies contact Mr Bernie Doran via Telegram : @Bernie_fx or Email : Bernie.doranfx01@gmail.com

    ReplyDelete
  9. If you're planning a trip to the picturesque town of Manali, exploring the best Manali tour packages can ensure a hassle-free and memorable experience. Manali, nestled in the beautiful Himalayan region of Himachal Pradesh, offers many attractions and activities that cater to all kinds of travelers.


    Read more : https://lockyourtrip.com/packages/manali/tour-packages/


    ReplyDelete
  10. wow! it was very nice article. Thank you for sharing.
    visit:sql server dba training

    ReplyDelete
  11. Thank you! I read the blog post, it's truly amazing, I must say if want more knowledge about ISO tank operation software visit our domain Seaknotsit. Your blog added some value to my knowledge. Keep it up.

    ReplyDelete