Angular 无法在组件使用 Material 自动完成的 displayWith 组件方法中访问 "this"

Angular Cannot access "this" in displayWith component method where component uses Material Autocomplete

在 Angular 的最新版本中,我使用了以下 HTML:

    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngFor="let entity of entityNames" [value]="entity.EntityId">
     {{ entity.EntityName }}
    </mat-option>

在我的常规 angular 组件中,displayFn 方法如下所示:

displayFn(entityId: number): string {
  const name = (entityId && entityId > 0) ? this.entityNames?.find(entityName => entityName.EntityId === entityId).EntityName : '';
  return name;
}

问题是,我的组件“this”。不可用,对其成员的任何访问都失败。

简短的回答很简单:将 HTML 中的 displayFn 方法调用更改为添加 .bind(this),如下所示:

    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
      <mat-option *ngFor="let entity of entityNames" [value]="entity.EntityId">
        {{ entity.EntityName }}
      </mat-option>
    </mat-autocomplete>

我刚刚花了 2 天时间才发现“这个”。当该方法还用作 material 形式 在该组件 中的 displayWith 回调时,该方法在组件方法中不可用。我现在知道您可以在 HTML 中使用 displayFn.bind(this),但实际上为什么不将其作为回调的默认行为,因为可以肯定的是,任何不想使用的人都会,好吧,不会用吗?与此同时,人们 100% 的时间想要使用它,他们将不得不添加愚蠢的 .bind(this)。愚蠢的。真的。