在下面的代码中,我的国家/地区选择选项被触发多次,导致浏览器停止响应。
<div [formGroup]="countryForm">
<mat-form-field>
<mat-select formControlName="selectedCountry" class="my-item-text" placeholder="Country">
<mat-option (onSelectionChange)="onCountrySelectionChanged($event)" *ngFor="let myCountry of countries" [value]="myCountry.short" class="my-item-text">{{ myCountry.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
我的组件代码如下
onCountrySelectionChanged(changeEvent) {
if (changeEvent && changeEvent.isUserInput && this.selectedCountry != changeEvent.source.value) {
this.countrySelected.emit( changeEvent.source.value);
}
}
我尝试通过检查其用户更改事件 [isUserInput] 并检查值是否确实更改来进行限制!现在我能够减少火灾事件并且应用程序可以正常工作。
是否有更好的方法来使用 select-option,因为我现在在使用 mat-select 组件的任何地方都包含上述逻辑。
最佳答案
mat-select
有一个可以绑定(bind)到名为 selectionChange
的输出属性,只要用户更改选项,就会触发该属性。尝试将您的代码切换为:
<div [formGroup]="countryForm">
<mat-form-field>
<mat-select (selectionChange)="onCountrySelectionChanged($event)" formControlName="selectedCountry" class="my-item-text" placeholder="Country">
<mat-option *ngFor="let myCountry of countries" [value]="myCountry.short" class="my-item-text">{{ myCountry.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
想一想 - 可能发生的情况是,您已将 onSelectionChange
绑定(bind)放在每个 mat-option
上,因此当您更改选项时,您可能会为您选择的每个选项触发一次。将其移至 mat-select
意味着它只会触发一次。
关于angular-material - 升级到 Angular 6、 Material 6 后,选择选项事件连续触发并且浏览器挂起。如何阻止不需要的发射事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666669/