我们使用 创建了一个组件 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/