Why ngModelChange event triggering whenever focus in and out on the input box?

6k Views Asked by At

sample.html

<input #gb type="text" pInputText class="ui-widget ui-text" [(ngModel)]
="filterText"  (ngModelChange)="filterText = $event; clearFilter(filterText)"/>

componenent.ts

 clearFilter(value) {
                alert(value);// values is empty
            }

This alert will be fire every focus (in | out) on the input filed . I want to do hit the function if the model object had any changes.

How to handle it and Why ngModelChange event triggering while focus in and out on the input box?

2

There are 2 best solutions below

14
On

Because their work is to handle changes in the text box you have focus and blur methods

<input #gb type="text" pInputText class="ui-widget ui-text" 
  [(ngModel)] ="filterText" 
  (ngModelChange)="clearFilter(filterText)"
  (blur)="clearFilter($event)"
  (focus)="clearFilter($event)"/>

LIVE DEMO

Update based on comment

Since you are using [(ngModel)] and (ngModelChange) it is triggering.

0
On

The solution is trackBy if ngModel value change when you use *ngFor

Demo here: https://stackblitz.com/edit/angular-zwnges?file=app%2Fapp.component.html