gpt4 book ai didi

angular - 为什么 onSelectionChange 被调用两次?

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:10 25 4
gpt4 key购买 nike

我使用 Angular Material Autocomplete 如下:

<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() 被调用了两次。第二次使用值!我不明白为什么。这里发生了什么?

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

> 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

最佳答案

对于 ma​​t-select 中的 ma​​t-option 我遇到了同样的问题,并以这种方式修复:

模板

<mat-select>
<mat-option (onSelectionChange)="handleMetaSignalChange(metaSignal.name,$event);" *ngFor="let metaSignal of metaSignals" [value]="metaSignal">
{{ metaSignal.name }}
</mat-option>
</mat-select>

代码

 handleMetaSignalChange(metaSignal: string, event: any) {
if (event.isUserInput) { // ignore on deselection of the previous option
console.log('Meta Signal Changed to ' + metaSignal + event.isUserInput);
}
}

关于angular - 为什么 onSelectionChange 被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53009998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com