Get & Set in Lightning Web Component

In this session, we will learn how to use get & set method in Lightning Web Component.

Generally, GET method returns value and SET method sets the value. We will follow the same way as in other OOPS Programming Language, JAVA.

To understand this exercise, we will see when user will give any input in the message box, the same i/p message will be visible in the output as read only.

We have created a Lightning Web Component named “getterSetter“.

Step 1: First, we have updated the getterSetter.js-meta.xml to set the visibility in Lightning App Builder.


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="" fqn="getterSetter">

Step 2: Need to update the html file.


    <lightning-card title = "Getter Setter Mechanism" icon-name="utility:bucket">          
                <lightning-layout-item flexibility="auto" padding="around-small">               
<div class="padding-around:small">
                        <lightning-input label="Message" value={message} onchange={handleMessage}></lightning-input>

<div class="padding-around:small slds-m-top_small">
                        <lightning-formatted-text value={outputMessage} ></lightning-formatted-text>


Here, we have taken lightning-input base component to take the input from user and lightning-formatted-text base component to show the output. The respective attributes are message and outputMessage.

Step 3: Now, we have updated the JS file.


import { LightningElement, track } from 'lwc';

export default class GetterSetter extends LightningElement {

    defaultMsg = "We are learning ";
    @track outputMessage;

    get message(){
        return this.defaultMsg + "Lightning Web Component";

    set message(val){
       this.outputMessage = val;

        this.message =;


Here, we have declared one private attribute named defaultMsg which will store the default content. We have defined get and set for message property. So, System will return the message as “We are learning Lightning Web Component” and set the message to show in the output layer.Whenever user will write any thing, at this point of time handleMessage(event) function will be invoked, the value of message will be updated.

In theĀ handleMessage(event) function, we have assigned the latest message value to this.message property. When we have assigned message property in this function, set method will be automatically invoked.

Step 4: At last, need to add this LWC into Lightning App Page.


65,653 total views, 6 views today

Rating: 4.4/5. From 18 votes.
Please wait...
This entry was posted in Lightning Web Component. Bookmark the permalink.

Leave a Reply