2

在下面的代码中,我的国家选择选项被触发了很多次,以至于浏览器停止响应。

<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] 并检查值是否真的改变来进行限制!现在能够减少火灾事件并且应用程序正常工作。

有没有更好的方法来使用选择选项,因为现在包括上面的逻辑,到处都在使用 mat-select 组件。

4

1 回答 1

5

mat-select有一个可以绑定到调用的 Output 属性,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绑定放在每个 single 上mat-option,因此当您更改选项时,您可能会为您选择的每个选项触发一次。将其移出mat-select意味着它只会触发一次。

于 2018-06-04T09:20:14.220 回答