Angular无法在组件使用Material Autocomplete的displayWith组件方法中访问“this”

Kim*_*tes 1 autocomplete callback this angular-material angular

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

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

在我的常规角度分量中,该displayFn方法如下所示:

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

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

Kim*_*tes 5

简短的答案很简单:更改displayFnHTML 中的方法调用,添加.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>
Run Code Online (Sandbox Code Playgroud)

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

  • 长长的答案是,当这个代码被编码时,Angular 已经把头埋在了某个地方。完全没有价值。 (2认同)