Where To We Add Evenent In Lightning
In this mail service nosotros volition talk about how to use the lightning spider web component events to communicate between components. Events in Lightning web components are built on DOM Events, a collection of APIs and objects bachelor in every browser. Here nosotros will be see how to the events using the CustomEvent interface and publish-subscribe utility.
Component Advice through events
There are typically 3 approaches for communication between the components using events.
- Communication using Method in LWC ( Parent to Child )
- Custom Result Communication in Lightning Web Component (Child to Parent )
- Publish Subscriber model in Lightning Web Component ( Two components which doesn't have a direct relation )
Note:- If yous want to communicate the Lightning spider web component with Visualforce page then we tin can employ Lightning Message Service (LMS).
Option one) Communication using Method in LWC (Parent to Child)
In Aureola framework, we tin call the method of Child Component from the Parent Component with the aid of <aura:method> (Please cheque this post for <aura:method in aura). In LWC also we can practice the same. In LWC Aura Methods Go JavaScript Methods.
For this we have utilise the @api decorator to make the children backdrop / method public bachelor so parent tin be able to call information technology straight using JavaScript API. For example create one public method (which we need to access in parent component) in ChildComponent with @api decorator like below
ChildComponent
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}
To access the above child method in parent component nosotros can do like that.
ParentComponent
this.template.querySelector('c-kid-component').changeMessage(event.target.value);
The querySelector() method is a standard DOM API that returns the starting time chemical element that matches the selector
Lets take one example to pass value from parent component to child component.
- Create one kid Component to show message from parent component.
childComp.html
<template>
Bulletin Will Come here from Parent Component :- {Message}
</template> - Create javaScript method in child component to assign value on child attribute. childComp.js
import { LightningElement, rail, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@track Bulletin;
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}
} - Create one Parent Component to telephone call child component.
ParentComponent.html
<template>
<lightning-bill of fare championship="Parent to Child Demo">
<lightning-layout><lightning-layout-item flexibility="auto" padding="around-small" >
<lightning-input label="Enter the Message" onchange={handleChangeEvent}></lightning-input>
</lightning-layout-item><lightning-layout-particular flexibility="auto" padding="around-small">
<c-child-Comp></c-kid-Comp>
</lightning-layout-item></lightning-layout>
</lightning-carte>
</template> - Now Create JavsScript method in Parent component to call child method with "this.template.querySelector".
ParentComponent.js
import { LightningElement } from 'lwc';
export default grade ParentComponent extends LightningElement {
handleChangeEvent(event){
this.template.querySelector('c-child-Comp').changeMessage(event.target.value);
}
} - Update your meta.js file to make this component bachelor for App, home page.
ParentComponent.js
<?xml version="one.0" encoding="UTF-viii"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="parentComponent">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output :
Selection 2) Custom Outcome Communication in Lightning Web Component (Kid to Parent)
Nosotros already talk about Event in Aura. Lets talk virtually Lightning Spider web Components (LWC), here Custom Event is used to make the communication from Kid Component to Parent Component. With LWC we tin can create and acceleration the custom issue.
-
Create and Dispatch an Outcome
-
Create Effect : Nosotros tin employ the customEvent() constructor to create an event. In constructor nosotros need to pass custom outcome name and detail of the event.
new customEvent(eventName, props);
-
Dispatch Event : We have to dispatch an event at with EventTarget.dispatchEvent() method.
this.dispatchEvent(new customEvent(eventName, props);
-
-
Handle an Consequence : There are two means to heed to an outcome
-
Declarative via html markup : We need to add "on" prefix in the outcome name in Parent Component during calling of Child Component for Declaratively event listener.
ParentComponent
<template>
<c-child-component oneventName={listenerHandler}></c-kid-component >
</template> -
JavaScript using addEventListener method : West eastward can explicitly attach a listener by using the addEventListner method in the parent component like below :
ChildComponent
this.template.addEventListener('eventName', this.handleNotification.bind(this));
-
Lets take one case for "Declarative via html markup"
- Create one child component component from where nosotros will raise a outcome
- Create kid html file to get value from user.
childComp.html
<template>
<lightning-card title="Child Component">
<div class="slds-m-around_medium">
<lightning-input name="textVal" label="Enter Text" onchange={handleChange}></lightning-input>
</div>
</lightning-card>
</template> - Now update Child Comp javaScript file to enhance a CustomEvent with text value
childComp.js
import { LightningElement } from 'lwc';
export default class ChildComp extends LightningElement {
handleChange(event) {
event.preventDefault();
const name = event.target.value;
const selectEvent = new CustomEvent('mycustomevent', {
detail: proper noun
});
this.dispatchEvent(selectEvent);
}
} - Create one Parent component where we will handle the event
- Now create parent component. We need to add prefix as "on" earlier the custom result name and in parent component we need to invoke the event listener as handleCustomEvent using onmycustomevent attribute.
ParentComponent.html
<template>
<div class="slds-m-around_medium">
Value From Child : {msg}
<c-child-comp onmycustomevent={ handleCustomEvent}></c-kid-comp>
</div>
</template> - At present update parent component javaScript file and add together handleCustomEvent method.
ParentComponent.js
import { LightningElement , track } from 'lwc';
export default class ParentComponent extends LightningElement {
@track msg;
handleCustomEvent (consequence) {
const textVal = event.detail;
this.msg = textVal;
}
}
Output :-
Lets run across how we can use "JavaScript using addEventListener method | Attaching event Listener Programmatically"
- We tin use the same higher up sample and do below change in parent component
- Update parent component JavaScript similar beneath.
ParentComponent.js
import { LightningElement , rail } from 'lwc';
export default class ParentComponent extends LightningElement {
@track msg;constructor() {
super();
this.template.addEventListener('mycustomevent', this.handleCustomEvent.demark(this));
}handleCustomEvent(outcome) {
const textVal = outcome.detail;
this.msg = textVal;
}
} - Remove onmycustomevent aspect from child component tag. like beneath
ParentComponent.html
<template>
<div grade="slds-m-around_medium">
Value From Kid : {msg}
<c-kid-comp ></c-child-comp>
</div>
</template> - Set the bubbles: true while raising the outcome like below
childComp.js
import { LightningElement } from 'lwc';
consign default course ChildComp extends LightningElement {
handleChange(event) {
event.preventDefault();
const name = event.target.value;
const selectEvent = new CustomEvent('mycustomevent', {
particular: proper name ,bubbles: true
});
this.dispatchEvent(selectEvent);
}
}
Effect Propagation: When an result is fired the consequence is propagated up to the DOM. Issue propagation typically involves 2 phases outcome bubbling and upshot capturing. The most commonly used consequence propagation phase for handling events is event bubbles. In this case the event is triggered at the child level and propagates up to the DOM. Where every bit event capturing phases moves from acme to bottom of the DOM. This stage is rarely used for upshot handling.
The below picture shows the event phases both in capture and bubbles phase. In LWC we have ii flags which determines the beliefs of event in result bubbling phase.
- bubbles A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.
- composed A Boolean value indicating whether the outcome tin can pass through the shadow boundary. Defaults to fake.
reference: https://developer.salesforce.com/docs/component-library/documentation/lwc/events_propagation
Choice 3) Publish Subscriber model in Lightning Spider web Component
Awarding Events in aura become a Publish-Subscribe Pattern in Lightning web components. We use an library called pubsub to accomplish the communication betwixt two components which doesn't accept a direct relation to each other. This works like a typical publish subscribe model. Where an consequence is subscribed past a component and handled when some other component which fires/publishes the event inside the same scope.
Please use this link to become the pub sub utility code. Pubsub module support below three method
- Register
- UnRegister
- Burn down
Follow below step for Pub Sub module
-
Import Pub Sub file from here.
-
Register the Result
- Add JavaScript Code in Component to register and unregister the issue. In this JS file, invok registeredListener() and unregisterAllListeners() in the corresponding methods such as connectedCallback() and disconnectedCallback().
MyComponent.js
import { registerListener, unregisterAllListeners} from 'c/pubsub';
export default class MyComponent extends {@rails Bulletin;
connectedCallback() {
registerListener('messageFromSpace', this.handleMessage, this);
}handleMessage(myMessage) {
this.Bulletin = myMessage;
//Add together your lawmaking here
}disconnectCallback() {
unregisterAllListeners(this);
}
} -
Fire the event
- Fire the event from other Component. In that js file, We demand to trigger the event with proper noun and value. Remember, nosotros also need to ship the folio reference attribute as current page reference for successful advice
OtherComponent.js
import { fireEvent } from 'c/pubsub';
import { CurrentPageReference } from 'lightning/navigation';
export default course OtherComponent extends LightningElement {
@track myMessage;
@wire(CurrentPageReference) pageRef;sendMessage() {
fireEvent(this.pageRef, 'messageFromSpace', this.myMessage);
}
}
Please check below post on Lightning Web Components:-
- Lightning Spider web Components ( LWC ) in Salesforce with Non-Scratch Org
- Invoke Noon Controller from Lightning Web Component | Lightning Web Component inside Another LWC
- Pattern attributes in Lightning Web Components | CSS and SVG Files | Lightning Web Components | targetConfigs
- How to go electric current user id in lightning web component | Access logged in user ID in LWC
- Toast Notification in Lightning Spider web Components | ShowToastEvent | (LWC)
- Lightning Web Components Best practices
- Lightning datatable In Lightning Web Components | lightning datatable inline edit
- Lightning Message Service (LMS) | MessageChannel
Thanks,
Amit Chaudhary
Where To We Add Evenent In Lightning,
Source: http://amitsalesforce.blogspot.com/2019/07/events-in-lightning-web-components-lwc.html
Posted by: massasady1977.blogspot.com
0 Response to "Where To We Add Evenent In Lightning"
Post a Comment