css - 方法在 Angular Material 自动完成中被多次调用

标签 css angular autocomplete angular-material 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;
}

最佳答案

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

示例:Stackblitz

N.B:我们知道当我们改变选择的值时它会触发一个事件改变,我们可以计算它并将计算结果附加到 [class.my-class] 或 ngClass。

关于css - 方法在 Angular Material 自动完成中被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57856800/

相关文章:

javascript - 正确的 Canvas 高度和宽度未传递给函数

html - 无法读取未定义的属性 'nativeElement' - ngAfterViewInit

javascript - 如何将 jQuery ui 自动完成添加到动态内容?

java - Glazed List 和 Nimbus 中的背景色

javascript - Jquery - 将事件添加到与其他人共享类名的特定 div

html - CSS:IE6 和多个 div 并排出现问题,元素在右浮动

html - bootstrap 3 不应用 panel-primary 作为蓝色背景色

angular - ngClass 没有得到应用

angular - 如何刷新组件

javascript - 在不提交表单的情况下使用 ngClick 触发自动完成