ngModelOptions directive for performance optimization in Angular forms

devmichaljdevmichalj
1 min read

The updateOn property allows you to specify when the model should be updated. By default, Angular updates the model on each input event. However, with ngModelOptions, you can configure it to update on different events such as blur or submit.

Let's go through an example of using the ngModelOptions directive with the updateOn property in an Angular template-driven form:

<!-- simple-form.component.html -->
<form #myForm="ngForm">
  <label for="name">Name: </label>
  <input
    type="text"
    id="name"
    name="name"
    ngModel
    [ngModelOptions]="{ updateOn: 'blur' }"
  />

  <pre>Current Value Form Object: {{ myForm.form.value | json }}</pre>
  <button type="submit">Submit</button>
</form>

Explanation

  1. ngModelOptions with updateOn: 'blur':

    • The ngModelOptions directive in Angular allows you to configure how ngModel updates its bound model value. When you specify { updateOn: 'blur' }, it means that the model associated with the input field will be updated only when the input field loses focus (when the blur event occurs).
  2. Current Form Model object:

    • The current value of the Form Model object is displayed below the input field. This helps in demonstrating how the model value changes only after the input loses focus.

Conclusion

By using ngModelOptions with updateOn: 'blur', you can control when Angular updates the model. This is particularly useful for performance optimization in forms with heavy data-binding or when you want to prevent frequent model updates during user input.

0
Subscribe to my newsletter

Read articles from devmichalj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

devmichalj
devmichalj