gpt4 book ai didi

angular - md-autocomplete onSelectionChange 触发了两次

转载 作者:太空狗 更新时间:2023-10-29 17:11:51 27 4
gpt4 key购买 nike

我在 Angular 应用程序中使用 md-autocomplete angular/material: 2.0.0-beta.5。在最新版本中,selected 方法已被 onSelectionChange 取代。

第一次从下拉列表中选择一个值时,关联的方法只被触发一次,但如果我从下拉列表中选择一个新值,它会被选择两次(第二次具有前一个值)。

逻辑在以前的版本中工作正常。

模板

<md-autocomplete #panel="mdAutocomplete" [displayWith]="displayFn">
<md-option (onSelectionChange)="selected(country)" *ngFor="let country of filteredCountries | async" [value]="country">
<div class="selector-elements">
<span>
<img [src]="getFlagPath(country.code)" [width]="24" [height]="24" />
</span> {{ country.name }}
</div>
</md-option>

控制者

export class CountrySelector implements OnInit, ControlValueAccessor {

// ...

initCountries() {
this.countryList = countryNames;

this.filteredCountries = this.formControlName.valueChanges
.startWith(null) //-> OnInit the countries are filtered by null, hence all results are returned.
.map(country => {
return country && typeof country === 'object' ? country.name : country
})
.map(name => name ? this.filter(name) : this.countryList.slice());
}

filter(val: string): ICountry[] {
//Regex to match with the first letters of the country name with the passed value.
return this.countryList.filter(country => new RegExp(`^${val}`, 'gi').test(country.name));
}

resetCountrySelection(){
let country = new Country();
this.formControlName.setValue(country);
this.propagateChange(country);
}

writeValue(country: Country): void {
if (country) {
this.formControlName.setValue(country);
}
}

selected(country: ICountry) {
// Here it gets triggered twice when a new element is chosen
this.propagateChange(country);
}

propagateChange = (_: any) => { };

registerOnChange(fn: any) {
this.propagateChange = fn;
}

}

最佳答案

发生的事情是 onSelectionChange 按顺序为新选中的和未选中的触发。如果你像这样将 $event 添加到你的电话中

(onSelectionChange)="selected($event, country)"

然后你可以通过这样查看源来检查它是否是被选中的

selected(event: MdOptionSelectionChange, country: ICountry) {
if (event.source.selected) {
this.propagateChange(country);
}
}

关于angular - md-autocomplete onSelectionChange 触发了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056913/

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