EVENTS IN Lightning Web Components

Events in Lightning web components (LWC) | Communicate with Events


In this post we will talk about how to use the lightning web component events to communicate between components. Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser. Here we will be see how to the events using the CustomEvent interface and publish-subscribe utility.

COMPONENT COMMUNICATION THROUGH EVENTS
There are typically 3 approaches for communication between the components using events.

  1. Communication using Method in LWC ( Parent to Child )
  2. Custom Event Communication in Lightning Web Component (Child to Parent )
  3. Publish Subscriber model in Lightning Web Component ( Two components which doesn't have a direct relation )
 1) COMMUNICATION USING METHOD IN LWC (PARENT TO CHILD)
In Aura framework, we can call the method of Child Component from the Parent Component with the help of <aura:method> . In LWC also we can do the same. In LWC Aura Methods Become JavaScript Methods.

For this we have use the @api decorator to make the children properties / method public available so parent can be able to call it directly using JavaScript API. For example create one public method (which we need to access in parent component) in ChildComponent with @api decorator like below

Child Component
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}

In order to access that above child method in the parent component, we can do that.

ParentComponent. this.template.querySelector('c-child-component').changeMessage(event.target.value);

The querySelector() method is a standard DOM API that returns the first element that matches the selector.

Let us take one example to pass value from parent component to child component.

childComp.html

<template>
Message Will Come here from Parent Component:- { Message}
</template>

2. Create a javaScript method in the child component to assign a value on child attribute. childComp.js

import { LightningElement, track, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@track Message;
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}
}
3. Create one Parent Component to call child component.

ParentComponent.html

4.Now Create JavsScript method in Parent component to call child method with “this.template.querySelector”.

ParentComponent.js

import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
handleChangeEvent(event){
this.template.querySelector(‘c-child-Comp’).changeMessage(event.target.value);
}
}
5. Update your meta.js file to make this component available for App, home page.
ParentComponent.js

Comments

Popular posts from this blog

Security model

Lightning web Components.