LWC engine can track changes or value assigned to a field or primitive properties automatically, however if field/properties is array or object type then LWC will not be able track value change automatically.
That is when @track is helpful, this will tell LWC engine to observe changes to the properties of object or elements of array decorated with @track.
Here is my component code
We can also achieve using spread operator, the key here is instead of mutating same object/array we can create copy and make changes. LWC framework observes value assigned to field/property and if new value !=== previous value then component re-renders.
this.address = {...this.address,"city":event.target.value}
<template>
<lightning-card title="2 way Data Binding">
<div class="slds-m-around_medium">
<lightning-input type="text" label="Enter course Name"
onkeyup={changehandler}></lightning-input>
<div>{fullname} is course of {title}</div>
</div>
</lightning-card>
<lightning-card title="@track properties">
<div class="slds-m-around_medium">
<lightning-input type="text" label="Enter City Name"
onkeyup={trackhandler}></lightning-input>
<div>{address.city} is my city</div>
</div>
</lightning-card>
</template>
Java script code
import { LightningElement,track } from 'lwc';
export default class HelloWorld1 extends LightningElement {
fullname = "LWC Learning"
title ="aura"
@track address = {
city:"Louisville",
postalCode:40291,
country:"USA"
}
@track hobbies = ['Music','Reading','Netflix'];
changehandler(event){
this.title = event.target.value;
}
trackhandler(event){
//this.address = {...this.address,"city":event.target.value}
this.address.city=event.target.value;
}
}
No comments:
Post a Comment