Reputation: 3427
I have a scenario whenever the user starts searching for something which will call the HTTP service and get the response and show it in the dropdown.
I have the below code which is working fine with the above approach. But, after we click any option listed from the dropdown, ngmodelchange
method again calling which fetch the service again. It should not happen.
Where am I missing?
<mat-form-field class="half-width">
<input matInput aria-label="State" name="state" placeholder="Search by number (1 or 2 or 3)" [matAutocomplete]="auto" [(ngModel)]="currentState"
(ngModelChange) = "filterInstrument(currentState)">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="state">
<mat-option *ngFor="let state of insDetails" [value]="state.id">
<span>{{state.id}}</span> |
<span>{{state.userId}}</span> |
<span>{{state.title}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
Complete Code in stackblitz
Upvotes: 0
Views: 2789
Reputation: 226
Try using the (input) event instead of the (ngModelChange)
Explanation :
The "input" event, is a synchronous event that is triggered as the user is interacting with the text-based input controls. Meaning, it doesn't wait for a blur event to calculate the value-change - the input event is triggered immediately after any mutation of the value property (whether it be through user key-stroke events or user paste events).
Upvotes: 2
Reputation: 739
Try changing the ngModelChange
event to keypress
event
<mat-form-field class="half-width">
<input matInput aria-label="State" name="state" placeholder="Search by number (1 or 2 or 3)" [matAutocomplete]="auto" [(ngModel)]="currentState"
(keypress) = "filterInstrument(currentState)">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="state">
<mat-option *ngFor="let state of insDetails" [value]="state.id">
<span>{{state.id}}</span> |
<span>{{state.userId}}</span> |
<span>{{state.title}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
ngModelChange gets called if there is a change in the input value but the keypress event gets called once you type any value
Upvotes: 3