1. Create a LWC component named as "getterSetterExample". Where getterSetterExample.js has a getter and a setter method for "greetingMessage" and in "getterSetterExample.html" we will call "greetingMessage" message
to display.
getterSetterExample.html
<template>
{greetingMessage}
</template>
getterSetterExample.js
import { LightningElement, api } from 'lwc';
export default class GetterSetterExample extends LightningElement {
//Get method use to return greeting message.
@api
get greetingMessage(){
return this._greetingMessage;
}
//Set method use to setup greeting message in upper case.
set greetingMessage(value){
this._greetingMessage = value.toUpperCase();
}
}
2. Now call this "
getterSetterExample" component from "
useGetterSetter" component.
useGetterSetter.html
<template>
<lightning-card title="Getter Setter Example">
<lightning-layout>
<lightning-layout-item>
<!-- Passing greeting-message in small letter and expected result: message will be shown in capital letter. -->
<c-getter-setter-example greeting-message="hello everyone. welcome to lwc getter setter example."></c-getter-setter-example>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
Now to make this useGetterSetter available in AppBuilder/Record Page/Home Page, please update "
useGetterSetter.js-meta.xml" file as below,
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="useGetterSetter">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
3. Then open any existing appBuilder / create a new one and drag the <
useGetterSetter> in to respective column and then save and activate it. Now click the tab to show it in browser and it will look as follows,
4. So, we are passing value of "
greeting-message" property of "
getterSetterExample" LWC component from "
useGetterSetter" LWC component, in small letter as "
hello everyone. welcome to lwc getter setter example.".
Now this message will be set in upper case in setter method of "
getterSetterExample.js" file and from getter method it will return the value.
So, while calling child component (
getterSetterExample) from parent component (
useGetterSetter) with above message (
in small letter), then system will display the message in capital letter. And the output is as follows,