简体   繁体   English

在角材料中选择了mat-option时调用ngmodelchange

[英]ngmodelchange called when mat-option selected in angular material

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. 每当用户开始搜索将调用HTTP服务并获取响应并将其显示在下拉列表中的内容时,我都会遇到这种情况。

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. 但是,在单击下拉列表中列出的任何选项后, ngmodelchange方法将再次调用来再次获取服务。 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 Stackblitz中的完整代码

Try changing the ngModelChange event to keypress event 尝试改变ngModelChange事件keypress事件

<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 ngModelChange被调用,如果有输入值发生变化,但一旦你输入任何值按键事件被调用

Try using the (input) event instead of the (ngModelChange) 尝试使用(输入)事件而不是(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). 这意味着,它不会等待模糊事件来计算值更改-在value属性发生任何更改后(无论是通过用户按键事件还是用户粘贴事件),都会立即触发输入事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM