bind-value-oninput instead of
bind in order to get real feedback as you type.
bind only databinds during the
onchange event which requires losing focus whereas
bind-value-oninput databinds on every keystroke. See line 3 below:
What is Blazor?
Scenario: Searching a List Client-Side
I want to build a Search feature that allows the user to search an unordered list (
<ul>), purely client-side. I don’t want to go back to the server to search, because in my scenario my data results are fairly small, don’t update often, and I want the response time to the user to be fast and avoid a round-trip. I was looking around and didn’t see much on the Interwebs showcasing this, which is why I wrote this post.
Note: This scenario could also be tweaked to search through a table (when pulling in a grid component is overkill), searching FAQs in an accordion, or really anything that needs a client-side search, it doesn’t have to be a list. The same concept applies.
Let’s build a simple component that loops over a list of ToDoItems and displays them in a list. You could imagine this could be used for a ToDo app, but I’m going to remove all the typical ToDo functionality (like checking off tasks as completed) since it will just add noise to this example.
It’ll look like this on the front-end:
And the component that powers it looks like this:
On line 3 we are taking an
input and using the
bind attribute to databind the input’s value to the
SearchTerm property. That
SearchTerm property is then used on line 30 to search through our
ToDoItems and return any matches in the
FilteredToDos property. Our list loops over the
FilteredToDos and displays them out. Let’s take a look how this works in real life with this gif:
What’s the problem? bind fires with onchange
By default, Blazor’s default
bind fires on the
onchange event. The
onchange event doesn’t fire until the input element loses focus. This means when a user types in the Search input they need to lose focus on the input before the Search takes place. While this is okay UX-wise, it’s not exactly ideal. My ideal world would be to have it fire while the user is typing so they can get real-time feedback without having to do any extra work (like clicking/tabbing out of the input or clicking a search button).
Solution: Use bind-value-oninput instead of bind
A little known feature about Blazor’s data binding is that
bind has options that let you bind to different events, not just
onchange. For our scenario, we want to databind to the
oninput event which fires immediately every time the value has changed. We can do this by swapping out
bind-value-oninput="@SearchTerm" on line 3 here:
Now when we run our app, we get a much better UX:
Hope this helps someone else in a similar scenario!