2

I am developing this feature that validate a user's input value of a look-up field and decide to clear it or not.

<lightning-input-field field-name="LOOK_UP__c" value={lookUpValue} onchange={handleChange}></lightning-input-field>
@track lookUpValue
handleChange(event) {
  // get the input look-up record id
  var id = event.detail[0]
  // save the id first
  this.lookUpValue = id
  if (!!id) { // validate if id has a value
    validField({Id: id}).then(result => {
      if (result == false) { // invalid, then clear the id
       this.lookUpValue = ''
      }
    }
  }
}

It turns out that the field is only rerendered for the first time. (It clears the field's display value). But if I select an invalid record once again, the field's display value is never cleared.

This is very odd, but when I find out this solution @Artem Klimanski answered:

setTimeout(() => {this.lookUpValue = ''}, 0);

It magically rerendered every time when a input look up value is invalid. It seems the asynch function is the trick.

I'm really curious about how it works and is there any document I can read or some should've known knowledge to pick up?

addition:

I only use the asynch function to set the value, the html element is remained without any change(unlike the answer I mention above). The code is now like this:

<lightning-input-field field-name="LOOK_UP__c" value={lookUpValue} onchange={handleChange}></lightning-input-field>
 // ...
 if (!!id) { // validate if id has a value
    validField({Id: id}).then(result => {
      if (result == false) { // invalid, then clear the id
       setTimeout(() => {this.lookUpValue = ''}, 0);
      }
    }
  }
  // ...

So it is not related to the <template if:true></template> for sure since I did not use this if tag.

2
  • I think it's because the lightning-input-field is removed and added once again on the UI because of the if:true condition, so then it is not considered to be dirty, as the user did not input any value after is rendered. There must be some attribute inside the component which is set to true when the user interacts for the first time, and when it is true it restricts the further rerenders. But when the component is removed and added from/to dom that flag is set to the default value. Mar 4 at 12:21
  • 1
    @rahulgawale thank you for your comment, please see the addition part.
    – Lanjinest
    Mar 4 at 13:17

Your Answer

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

Browse other questions tagged or ask your own question.