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)
问题是,我的组件“这个”。不可用,对其成员的任何访问都会失败。
简短的答案很简单:更改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). 愚蠢的。真的。
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |