Getter Property
Getter property is used when we want to modify the property before using it to the template. There is another use case when we do not want to create a variable in the component.
The getter function always executes after the constructor and connectedCallback in the lifecycle Hooks.
Syntax
get anyName() { … }
Let’s Play with the example
<template> <lightning-input type="number" name="input1" onchange={handleChange} label="Enter number" ></lightning-input> <lightning-input type="number" name="input2" onchange={handleChange} label="Enter number" ></lightning-input> <b>The sum {sumtwonumber}</b> </template>
In the above html we have two input fields will accept the number and the getter property will calculate the sum.
import { LightningElement, track } from 'lwc'; export default class salesforcedriller extends LightningElement { @track firstNumber; @track secondNumber; handleChange(event){ if(event.target.name==='input1'){ this.firstNumber = event.target.value; }else if(event.target.name==='input2'){ this.secondNumber = event.target.value; } } get sumtwonumber(){ //parseInt Converts a string to an integer. if(this.firstNumber && this.secondNumber){ return parseInt(this.firstNumber)+parseInt(this.secondNumber); } } }
Explanation: As you can see on the top there is a method called sumtwonumber with get property. Getter function with name sumtwonumber calculate the sum of those two properties dynamically. we have validated the input before processing it for sum.
Handlechange event will call when the input key is pressed by the USer.it will update the variables.
Output