Hello friends, In the earlier chapter we have learnt about types of component communication in lightning web component and parent child communication using public property.
In this chapter we are going to learn parent to child communication using methods in Lightning Web Component
- Parent to Child Communication using methods
- Query Selector
- QuerySelectorAll
- Scenario 1: Change content using querySelector
- Understanding code Line by Line for Scenario1
- Scenario 2: Change text color using querySelector
- Scenario 3: Change text color using querySelectorAll
- Scenario 4: Change text to uppercase using querySelector
Let’s Begin….
Basic Understanding of Public Method
- Public methods are methods annotated with the @api decorator.
- Public methods are part of the public API of the component, and can be called from a parent component
Meet the query selector Family
One of the most essential skills in our lightning web component development is finding elements in the DOM. We can do so by using:
- querySelector
- querySelectorAll
The querySelector and querySelectorAll functions are extremely useful in complex documents where targeting a particular element is often not straightforward.
querySelector() Method
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
Syntax
this.template.querySelector(CSS selectors)
Understanding Syntax
Template: To access elements rendered by a component, use the template property.
Elements not rendered to the DOM aren’t returned in the querySelector result.
Note: Don’t use the window or document global properties to query for DOM elements
eg: document.querySelector(CSS selector)
CSS Selector Examples
class selector
this.template.querySelector(".class-name");
tag selector
this.template.querySelector("div");
querySelectorAll() Method
Uses a CSS selector pattern and CSS selector rules to find a matching elements. Returns ALL elements that match the selector. If NO match is found, null is returned.
Syntax
this.template.querySelectorAll(CSS selectors)
CSS Selector Examples
class selector
this.template.querySelectorAll(".class-name");
tag selector
this.template.querySelectorAll("div");
Don’t use ID selectors with querySlector
The IDs that you define in HTML templates may be transformed into globally unique values when the template is rendered. If you use an ID selector in JavaScript, it won’t match the transformed ID.
Let’s understand the concepts with help of Scenarios
Code Design
child.html
<template> <!-- Created a h2 tag and added text --> <div class="slds-text-heading_medium">Change my text</div> </template>
child.js
//child.js import { LightningElement, api } from 'lwc'; export default class Child extends LightningElement { @api content; /* Created a method and used api decorator before it so as to expose it in parent component */ @api changeContent(){ this.template.querySelector('div').innerHTML="Hello Lightning Web Component!"; } }
Understanding Code Line by Line: HTML
Created a div tag and added text
Understanding Code Line by Line: JS
@api changeContent():
Created a method and used api decorator before it so as to expose it in parent component
this.template.querySelector(‘div’).innerHTML=”Hello Lightning Web Component!”;
this : If property is inside the class then use this. It specifies the current context
Template: To access elements rendered by a component, use the template property.
querySelector: The querySelector() method returns the first element that matches a specified CSS selector(s) in the document in this case it is <h2>
innerHTML: The innerHTML property sets or returns the HTML content (inner HTML) of an element.
In short, it gets the first <h2> element using querySelector and then change the text from “Change my text” to “Hello Lightning Web Component”
parent.html
<template> <lightning-card> <div class="slds-p-around_small"> <c-child content={mycontent}></c-child> <lightning-button label="Change Content" onclick={handleChangeContent}> </lightning-button> </div> </lightning-card> </template>
parent.js
import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { /* property in js */ mycontent; handleChangeContent(){ this.template.querySelector('c-child').changeContent(); } }
Understanding Code Line by Line: HTML
<c-child content={mycontent}>
As parent component that contains c-child (child component) so it can use methods of child component.
content : it is public property in child component exposed in parent component
mycontent: it is property in the parent component so given in braces
<lightning-button label=”Change Content” onclick={handleChangeContent}> </lightning-button>
I want on chick of button text should change, so I calling “handleChangeContent” on click
Understanding Code Line by Line: JavaScript
handleChangeContent()
It is method called on click of the button
this.template.querySelector(‘c-child’).changeContent()
Clicking the buttons in parent component will change the text after I call the method in the child component.
Here, changeContent() is the method in child component which is having logic to change text we are calling it from handleChangeContent() method of parent component
Scenario 2: Change text color using querySelector
child.html
<template> <h2>I am heading, color me </h2> <h2>I am another heading will you color me ?</h2> </template>
child.js
//child.js import { LightningElement, api } from 'lwc'; export default class Child extends LightningElement { @api colors; @api changeColor(){ this.template.querySelector('h2').style.backgroundColor = "red"; } }
child.css
h2{ font-size: 30px; }
parent.html
<template> <lightning-card> <div class="slds-p-around_small"> <c-child colors={coloring}></c-child> <lightning-button label="Color Me" onclick={handleClick}> </lightning-button> </div> </lightning-card> </template>
parent.js
import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { coloring; handleClick() { this.template.querySelector('c-child').changeColor(); } }
Using class- Instead of tag name we can also use class name
child.html
<template> <h2 class="example">I am heading, color me </h2> <br/> <h2 class="example">I am another heading will you color me ?</h2> </template>
child.js
@api changeColor(){ this.template.querySelector('.example').style.backgroundColor = "red"; }
Scenario 3: Change text color using querySelectorAll
child.html
<template> <h2>I am heading, color me </h2> <br/> <h2>I am another heading will you color me ?</h2> </template>
child.js
//child.js import { LightningElement, api } from 'lwc'; export default class Child extends LightningElement { @api colors; @api changeColorAll() { var x = this.template.querySelectorAll('h2'); console.log('x' +x); //x[object HTMLHeadingElement] for (var i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; } } }
parent.html
<template> <lightning-card> <div class="slds-p-around_small"> <c-child colors={coloring}></c-child> <lightning-button label="Color All" onclick={handleColorAll}> </lightning-button> </div> </lightning-card> </template>
parent.js
import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { coloring; handleColorAll() { this.template.querySelector('c-child').changeColorAll(); } }
Scenario 4 : Convert text to upperCase
child.html
<template> {updatedCase} </template>
child.js
//child.js import { LightningElement, api } from 'lwc'; export default class Child extends LightningElement { updatedCase; @api changeUpperCase(phrase){ this.updatedCase = phrase.toUpperCase(); } }
parent.html
<template> <lightning-card title="Converting text to uppercase"> <lightning-layout> <lightning-layout-item padding="around-small"> <lightning-input label="Input Phrase" onchange={handlePhraseChange}></lightning-input> </lightning-layout-item> <lightning-layout-item padding="around-small"> <label class="slds-text-body_regular">Output Phrase</label> <br/> <c-child></c-child> </lightning-layout-item> </lightning-layout> </lightning-card> </template>
parent.js
import { LightningElement } from 'lwc'; export default class Parent extends LightningElement { imgsrc="https://www.vhv.rs/dpng/d/2-27579_transparent-transparent-background-light-bulb-hd-png-download.png"; handlePhraseChange(event){ this.template.querySelector('c-child').changeUpperCase(event.target.value); } }
Conclusion: Practice creates confidence, confidence empowers you.
Together we can learn faster !
Join LWC study group on Telegram
Subscribe to Youtube channel and blog to get latest updates
Reference
Access Elements the component owns