Hi, in this blog I will show you an easier way to reference and access your LWC elements on the runtime.
Recently Salesforce has introduced a new way to do that in its Spring '23 release that is Template refs API
Template refs API provide you an easier way to reference your LWC elements and access it on JavaScript. And that is without using queryselector.
In this blog I will show you an example of how it was before this refs API and how you are going to use the new way of doing it. In below example I am having a Child and Parent composition and I am calling Child component's function from Parent component by accessing it on runtime using querySelector and refs API.
For the demo we will have a child component which will be having current timestamp and there will be a api refresh function which will refresh the timestamp. Using parent component we will be calling this refresh component in the child one and refreshing the timestamp.
Example 1: Old way using QuerySelector
child.html
1 2 3 4 5 6 7 | <template> <lightning-card title="I am child with API function " icon-name="utility:user"> <div class="slds-var-m-around_medium"> <p>{timestamp}</p> </div> </lightning-card> </template> |
child.js
1 2 3 4 5 6 7 8 9 10 11 | import { LightningElement,api } from 'lwc'; export default class Child extends LightningElement { timestamp = new Date(); @api refresh() { this.timestamp = new Date(); } } |
Parent.html
1 2 3 4 5 6 7 8 9 10 11 | <template> <lightning-card title="I am Parent with API function " icon-name="utility:user"> <div class="slds-var-m-around_medium"> <lightning-button label="Refresh" onclick={handleClick}> </lightning-button> <br/> <c-child></c-child> </div> </lightning-card> </template> |
Parent.js
1 2 3 4 5 6 7 8 | import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { handleClick() { console.log('###Handle Click'); this.template.querySelector('c-child').refresh(); } } |
Example 2: New way using refs API
Now let's see how it is going to be after using refs API in same example. Child component code will be same for this example so I will be just modifying Parent component below.
In parent component I have added lwc:ref="childcmp" in the composition.
Parent.html
1 2 3 4 5 6 7 8 9 10 11 12 | <template> <lightning-card title="I am Parent with API function " icon-name="utility:user"> <div class="slds-var-m-around_medium"> <lightning-button label="Refresh" onclick={handleClickPro}> </lightning-button> <br/> <!--Using lwc:ref as referenced Id for this component--> <c-child lwc:ref="childcmp"></c-child> </div> </lightning-card> </template> |
Parent.js
1 2 3 4 5 6 7 8 9 | import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { handleClickPro() { console.log('###Handle Click Pro'); this.refs.childcmp.refresh(); } } |
Output
Checkout complete video tutorial below
0 Comments