How do you change a text input from updating on every key stroke? With ngModelOptions it is really easy to control what event triggers the model update. In this lesson, we will modify a text input to update on blur instead of key up.
In this lesson, we are going to use ngModelOptions to only update the model of a text field when a blur event has happened, instead of updating it on every single keystroke.
A common scenario is when I'm working with a team of developers. Somebody comes up and asks me, "I want to update the model only after the user has left the text field and not on every single keystroke. That's simply too much. We need to dial it back."
With ngModelOptions, it is really, really easy to accomplish that. Let's hop into the code and see what we have here, real quick. We have a main controller as main. Then we have a main message that's bound to an input field. Then, in another div here, we have main.output.
Currently, when I type this, it immediately updates with every single keystroke. What we want to do is force that to only update when the user has removed focus from the text field, essentially the blur effect.
We'll hop back into the code. Using ng-model-options, we will pass in the model options object and say "updateOn." We'll set that to blur. Let's save the file and see this in action.
When I start typing, you can see it's no longer updating until I click out of the text field and it triggers that watch expression. Let me just take this off. You can see that it's updating every single time. Let me just put this back on. I tab out, and it is updated.
I also recommend checking out Kent Dodd's excellent series on ngModelOptions and the incredibly powerful things that you can do. I am covering just a specific scenario, but he really gets into detail about the amazing things you can do with this new feature on ngModel. This is just one tool in your toolbox. I look forward to seeing you in additional lessons.