There are a few different ways to get the current value of a field in LWC but which one is preferable and why?
For example, if I have an lightning input field called 'Footballer Name' on a LWC component, there are at least two ways I can get this in the .js file:
One is by leveraging the onchange specification like so (more info: https://salesforcediaries.com/2020/02/27/how-to-get-field-value-of-lightning-input-in-lightning-web-component-using-onchange-event/):
<lightning-input-field class="requiredInput" field-name="Footballer_Name__c" onchange={handleFootballerNameChange}>
and then in the .js file have:
handleFootballerNameChange(event) {
console.log('@@@ handleFootballerNameChange has been called');
this.formObject[event.currentTarget.fieldName] = event.target.value;
this.footballerName = event.detail.value;
}
Or we leverage the querySelector method like:
<lightning-input-field class="requiredInput" field-name="Footballer_Name__c" data-field="footballerName">
and then the .js file would look like:
let newValueOfFootballerName = this.template.querySelector("[data-field='footballerName']").value;
I notice that several repos from Salesforce have both versions and I can't find any documentation that suggests that one way is preferable over the other although it seems the former is more conventional.
I suppose a downside of using querySelector is that your HTML file will have lots of different Ids and that could become messy, especially if the field API name changes too as then you ideally would need to try and make sure the css Ids were named in a similar fashion.
I did wonder if querySelector is more performant as it doesn't raise an event but that seems a bit moot.