webworm
webworm

Reputation: 11019

Angular (change) event not firing on all changes

I have an Angular 7 app that contains a text input. The value of the text input is bound to a component level variable accountNumber.

<input type="text" [(ngModel)]="accountNumber" (change)="isAccountNumberFlagged(accountNumber)" />

I have a component method isAccountNumberFlagged(number: string) that checks to see if the accountNumber is flagged and if it is display a warning (by making a specific element visible. I have this method bound to the change event and it works as expected.

What doesn't work as expected is when I change the value in the text input after having entered a value that has been "flagged" and tab to another control. The (change) event does not fire in these cases.

Sequence of events

  1. Component loads
  2. Change the value in the text input = (change) event fires
  3. Enter a flagged account number = (change) event fires and flagged warning displays
  4. Change the value in the text input = (change) DOES NOT fire (even if I enter another or the same flagged account number)

Clearly I am missing something about how the (change) event works. What am I doing wrong?

Upvotes: 5

Views: 46901

Answers (1)

KShewengger
KShewengger

Reputation: 8269

You can choose 2 methods for this:

Have created a Stackblitx Demo for your reference

1.) Try to use (input) event handler instead.

<input type="text" 
       [(ngModel)]="accountNumber" 
       (input)="isAccountNumberFlagged(accountNumber)" />

2.) OR Separate your NgModel Input and Event Handlers

<input type="text" 
       [ngModel]="accountNumber"      // [] Input Binding
       (ngModelChange)="isAccountNumberFlagged($event)" /> // () Event Binding

// Be sure to update your accountNumber value inside the function
// to reflect such changes
isAccountNumberFlagged(accountNumber) {
   ...
   this.accountNumber = newValue;
}

Upvotes: 22

Related Questions