方法在角度材料自动完成中被多次调用

Pri*_*hra 5 css autocomplete angular-material angular angular7

我们已经使用Angular 材质自动完成功能创建了一个组件。为了显示选项,我们遍历了一个包含 51 个对象数组。我正在将 CSS 类应用于已选择的选项。该isAccountingTypeSelected方法确定选项是否被选中或没有。该方法被调用51*28 = 1428 次。我似乎不明白原因?它应该只被调用51 次,不是吗?

<mat-form-field class="full-width">
  <input type="text" matInput #autoCompleteInput [formControl]="autocompleteForm" [matAutocomplete]="auto" placeholder="Choose Accounting Type" aria-label="Number">

  <span matSuffix class="close-icon hover" *ngIf="autoCompleteInput.value" (click)="clearAll($event)"></span>
  <span matSuffix class="arrow-drop-down-icon hover" (click)="openPanel()"></span>

  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="accountingTypeSelected($event)">
    <mat-option *ngFor="let accountingType of filteredAccountingTypes | async" [value]="accountingType.code">
      <span class="accounting-type-options" [class.selected]="isAccountingTypeSelected(accountingType.code)">
        {{ accountingType.name + ' (' + accountingType.code + ')' }}
      </span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

isAccountingTypeSelected(code: string): boolean {
  console.log('I was called');
  if (this.selectedAccountingTypes.find((accountingType: AccountingType) => accountingType.code === code)) {
    return true;
  }

  return false;
}
Run Code Online (Sandbox Code Playgroud)

Md.*_*fee 4

Angular 多次使用 ChangeDetection 生命周期来检查 [class.selected] 或 ngClass 的函数是否已更改。如果使用函数,它会调用多次。因此,在绑定时不建议使用函数,而是应该计算 component.ts 文件中的值并将这些值绑定到 ngClass 或 [class]。

示例:堆栈闪电战

注意:我们知道当我们更改选定的值时,它会触发事件更改,我们可以计算它并将计算结果附加到 [class.my-class] 或 ngClass。