Using ngModelOptions to Update on Blur

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.

You must be a Member to view code

00:01 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.

00:16 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."

00:34 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.

00:57 If we hop into the JavaScript, you can see here that we have main.message, main.output, and then we have a watch expression where we are watching main.message. When main.message is changed or modified, then it changes main.output to message updated with the new value.

01:20 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.

01:39 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.

02:02 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.

02:30 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.