angular-material - 升级到 Angular 6、 Material 6 后,选择选项事件连续触发并且浏览器挂起。如何阻止不需要的发射事件?

标签 angular-material angular-material2 angular6 rxjs6

在下面的代码中,我的国家/地区选择选项被触发多次,导致浏览器停止响应。

<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/

相关文章:

angular - Angular 4 Material 是否像 Bootstrap 一样响应?

angular - 如何在生产构建中更改 Angular 应用程序脚本的路径?

Angular 国际化 - 带有 HTML 标签的 XLIFF

css - 垫表列宽度在包含输入时不会改变

angular-material - WebStorm @angular/material 数据表模板错误

angular - 找不到模块 '@angular/material-moment-adapter'

angular - 如何在 Angular 中@import CSS 文件?

html - 如何在动态数据表 Angular 中显示空消息

angular - 在垫日历中突出显示日期

angular - 如何在 Angular Material Grid 中设置行距?