0

I have two lightning input in a simple LWC component having respective onchange handlers and being @tracked with respective attributes. Second onchange handler is getting fired when I update second @track attibute from onchange handler of first input. Why?

HTML Code:

<template>
    <lightning-card>
        <lightning-input type="text" value={accountName} label="Enter Account Name" onchange={handleAccountNameChange}></lightning-input>
        <lightning-input type="text" value={contactName} label="Enter Contact Name" onchange={handleContactNameChange}></lightning-input>
    </lightning-card>
</template>

JS Code :

import { LightningElement, track } from 'lwc';
export default class LdsExample1 extends LightningElement {
    @track accountName;
    @track contactName;
    handleAccountNameChange(event){
        console.log('Account Name changed');
        this.contactName = 'N/A';
    }
    handleContactNameChange(event){
        console.log('Contact Name Changed');
    }
}

Here, When I am changing Account Name from UI, I am updating Contact Name to 'N/A' from JS, which is getting reflected in UI but why "handleContactNameChange" is not getting fired here?

Please help me in this. Can I add onhandle event listener on @track attribute in JS?

3

HTML specifies that onchange handlers only fire for UI (user) updates, not by JavaScript. This isn't a framework limitation or anything, just standard, default behavior of the standards. This prevents (trivially) wiring up infinite recursion problems. If you really want to respond to any change, use a setter:

_contactName;
get contactName() {
  return _contactName;
}
set contactName(value) {
  this._contactName = value;
  console.log('responding to change in attribute')
}
1

You no longer need the track decorator for your property to be reactive, regardless of if you are using it or not, your code should work:

tempalte:

<template>
    <lightning-input type="text" label="Enter Account Name" onchange={handleChange} value={account}></lightning-input>
</template>

JS file: import { LightningElement } from 'lwc';

export default class Input extends LightningElement {
    account = "account name";
    handleChange(event){
        console.log(event.detail.value)
    }
}

I did a quick copy paste, and the handle method fires on change of the input field value.

1
  • Hello, Kindly go through my ques, I am aware about @track changes in Spring 20 release. However, My question is regarding 2 way binding. Why event handler is not getting calling when track property is updated in JS. May 1 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.