The Lightning Web Components programming model has three decorators that add functionality to a property or function.
In this blog post we will learn the use of "@track decorator in Lightning Web Component".
@track is private reactive property. If there is a change in javascript property the component will rerender and all the expressions used in the template are reevaluated once again. Private Property can be used only in the component where it is defined.When we use the @track decorator, we must import it explicitly from lwc as shown below.
import { LightningElement, track } from 'lwc';
Let us understand with an example,
trackDecoratorTest.html
<template>
Name is: - {fname}
<br />
<lightning-input type="text" value={fname} onchange={handleChange} ></lightning-input>
</template>
trackDecoratorTest.js
/* eslint-disable no-console */
import {
LightningElement,
track
} from 'lwc';
export default class TrackDecoratorTest extends LightningElement {
@track fname = "Farukh Haider";
handleChange(event) {
this.fname = event.target.value;
console.log('Name change ' + this.fname);
}
}
TestLWCApp.app
<aura:application>
<c:trackDecoratorTest></c:trackDecoratorTest>
</aura:application>
Output:
Before Spring ’20, to make the component rerender when a user entered a fname, you had to decorate the fields with @track. Now if we remove the @track property as well there will not be any change in output.
trackDecoratorTest.js
/* eslint-disable no-console */
import {
LightningElement
} from 'lwc';
export default class TrackDecoratorTest extends LightningElement {
fname = "Farukh Haider";
handleChange(event) {
this.fname = event.target.value;
console.log('Name change ' + this.fname);
}
}
No comments:
Post a Comment