sarora
sarora

Reputation: 914

Using ngModelChange to update array of input fields

I'm trying to use ngModelChange to update the underlying data for an array of input fields, as shown in this stackblitz

However, when the ngModelChange function is triggered, updating the underlying data model prevents further data entry (e.g. try typing 123 in any field, and you will see only the first digit is accepted until you click the field again).

This kind of scenario (ngFor bound to array of fields) works easily with angular 2 way data binding, however, I need it to work with one-way-binding + ngModelChange so that I can do other things besides just updating the underlying data (e.g. as shown in the stackblitz, I trigger unsavedChanges flag to display a warning in the UI).

Any ideas how to make this work?

Note: I already explored S.O. for articles on ngModelChange / debounceTime e.g. ngModelChange / debounceTime

Based on those articles, I can see how using a Subject to push (debounced) changes in the ngModelChange function could work easily for single / static fields. However, in my scenario I have a dynamic array collection, and am not sure if I need to go down the route of an array of Subjects or a single Subject which contains an Array, or else if there's a more trivial solution to this whole problem (e.g. use 2 way binding but trigger another function somehow).

Any help greatly appreciated!

Upvotes: 0

Views: 359

Answers (1)

sarora
sarora

Reputation: 914

After further experimentation I found that debouncing changes to the data model still didn't solve the data entry issue, and that the real issue was the input field was losing focus after each change.

Apparently it's a known issue that you need to use a trackBy function when using an array of primitives, as detailed here

Upvotes: 1

Related Questions