【问题标题】:Angular Cannot access "this" in displayWith component method where component uses Material Autocomplete [duplicate]Angular无法在组件使用Material Autocomplete的displayWith组件方法中访问“this”[重复]
【发布时间】:2020-07-01 16:05:07
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您可以将回调定义为箭头函数:displayFn = (entityId: number): string =&gt; { ... }

标签: angular callback autocomplete angular-material this


【解决方案1】:

简短的回答很简单:将您在 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 天时间才发现“这个”。当该方法还用作displayWith 回调时,该方法在组件方法中不可用在该组件中。我现在知道你可以在 HTML 中使用displayFn.bind(this),但是当它可以保证任何不想使用的人都不会使用它时,为什么这不是回调的默认行为呢?与此同时,人们 100% 想要使用它,他们将不得不添加愚蠢的.bind(this)。愚蠢的。真的。

【讨论】:

  • 我想我记得有人说这是设计使然。另外,您不需要使用 .bind - 您可以使用带有箭头功能的包装器,如下所示:get displayFn() { return (val) =&gt; this.someProperty + val; }
猜你喜欢
  • 1970-01-01
  • 2018-08-05
  • 2018-02-23
  • 1970-01-01
  • 2020-07-12
  • 2021-08-29
  • 2021-04-17
  • 2019-04-05
  • 2020-10-09
相关资源
最近更新 更多