Updated: Jun 6
Lightning web components and Aura Components are like chalk and cheese, almost everything is different in LWC. To get started in LWC, reading input fields are really important. This article is going to explain all the ways user inputs can be read.
1. Using property -
We have bind a property "name" to lightning-input tag, and if any change happen in this field, it will call "nameChange" handler.
We have declared a track decorator "name", and in nameChange handler, assign the target value which call this handler.
2. Using getters -
In this example, we have a onchange handler on input field and we are getting value using "userName" getter.
When user enter something it will call nameChange handler, and will check the name of input filed, if it is "inp1", it will update name decorator. Getter "userName" will return the latest value of name decorator.
3. Using querySelector -
querySelector - returns the first element within the template that matches the specified selector, or group of selectors. If no matches are found, null is returned.
So, we have one input field (input1), a lightning button with onclick handler "handleClick".
The querySelector will find first "lightning-input" element. In next statement we are storing element value in decorator "name". Remember don't try to use querySelector with field name, because browser change the name to unique name and that will be different from what you have entered.
4. Using querySelectorAll -
querySelectorAll - returns a list representing a list of the template elements that match the specified group of selectors.
There are two lightning-input, a button which call handleClick.
in handleClick function, querySelectorAll will return a list of lightning-input element.
Next a forEach loop check each element name and assign to appropriate decorator.
Instead of using field type, we can also use class name in querySelectorAll.
both field have same class "inp".
rest of the code will be same.
Spring 20 Updates
The @track Decorator Is No Longer Required for Lightning Web Components
Click on below link for more information on @track