为什么 onSelectionChange 被调用两次? [英] Why is onSelectionChange called twice?

查看:47
本文介绍了为什么 onSelectionChange 被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular Material Autocomplete 如下:

I am using Angular Material Autocomplete as follows:

<mat-autocomplete #autocomplete="matAutocomplete" [displayWith]="displayFn" autoActiveFirstOption>
  <mat-option *ngFor="let option of filteredOptions$ | async" [value]="option" (onSelectionChange)="onSelectionChanged(option)" >
    {{displayFn(option)}}
  </mat-option>
</mat-autocomplete>    

这是处理程序:

onSelectionChanged(option) {
  console.log('Selected ' + option.name);
}

由于某种原因 onSelectionChanged() 被调用了两次.第二次使用值!我不明白为什么.这里发生了什么?

For some reason onSelectionChanged() gets called twice. The second time with the old value! I don't get why. What is happenning here?

依次选择第 1 项、第 2 项和第 3 项将打印:

Selecting item 1 and then item 2 and then item 3 will print:

> Selected item 1
> Selected item 2
> Selected item 1  // The unwanted call with the old value
> Selected item 3
> Selected item 2  // The unwanted call with the old value

推荐答案

材质有optionSelected事件你可以使用它

material has optionSelected event you can use it

<mat-autocomplete #autocomplete="matAutocomplete" (optionSelected)="onSelectionChanged($event)" [displayWith]="displayFn" autoActiveFirstOption>
 <mat-option *ngFor="let option of filteredOptions$ | async" [value]="option" >
    {{displayFn(option)}}
 </mat-option>
</mat-autocomplete>  

并以这种方式获得您的价值

and get your value that way

onSelectionChanged(event) {
   console.log(event.option.value);
}

这篇关于为什么 onSelectionChange 被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆