You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5中Material Autocomplete的displayWith函数this绑定问题

使用Angular Material Autocomplete的displayWith结合自定义函数

你这种思路完全没问题!displayWith的核心作用就是让你自定义选中项在输入框中的显示内容,把逻辑抽离到单独的getValue函数里是非常合理的代码组织方式,能让displayFn保持简洁清爽。

不过这里有个容易踩的小坑:要注意this的指向问题。如果直接把普通函数displayFn绑定到模板的[displayWith]上,有时候会因为上下文丢失导致this.getValue无法正确调用。下面给你两种可靠的解决方式:


方式1:用箭头函数绑定组件上下文

在组件类里把displayFn定义成箭头函数,这样就能确保this始终指向当前组件实例,不会出现调用异常:

// 组件类代码
displayFn = (id: number) => {
  return this.getValue(id);
};

getValue(id: number): string {
  // 这里写你的自定义逻辑,比如从选项数组中匹配对应文本
  const targetOption = this.options.find(opt => opt.id === id);
  return targetOption ? targetOption.name : '';
}

方式2:在模板中手动绑定this

如果还是习惯用普通函数写法,也可以在模板里通过bind(this)手动绑定上下文:

<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn.bind(this)">
  <mat-option *ngFor="let option of outletFilterOptions | async" [value]="option.id">
    {{ option.name }}
  </mat-option>
</mat-autocomplete>

对应的组件类函数保持你原来的写法即可:

displayFn(id: number) {
  return this.getValue(id);
}

getValue(id: number): string {
  // 你的自定义逻辑,返回对应id的显示文本
  return '匹配到的显示内容';
}

完整可运行示例

组件类代码

import { Component } from '@angular/core';
import { Observable } from 'rxjs';

interface OutletOption {
  id: number;
  name: string;
}

@Component({
  selector: 'app-outlet-autocomplete',
  templateUrl: './outlet-autocomplete.component.html',
})
export class OutletAutocompleteComponent {
  // 模拟门店选项数据
  outletList: OutletOption[] = [
    { id: 1, name: '中心门店' },
    { id: 2, name: '城东分店' },
    { id: 3, name: '城西分店' },
  ];
  outletFilterOptions!: Observable<OutletOption[]>;

  ngOnInit() {
    // 模拟异步过滤逻辑,实际可根据输入框值动态筛选
    this.outletFilterOptions = new Observable(observer => {
      observer.next(this.outletList);
    });
  }

  // 箭头函数确保this指向正确
  displayFn = (id: number) => {
    return this.getValue(id);
  };

  getValue(id: number): string {
    const matchedItem = this.outletList.find(item => item.id === id);
    return matchedItem ? matchedItem.name : '未找到匹配门店';
  }
}

模板代码

<mat-form-field appearance="fill" class="w-full">
  <mat-label>选择门店</mat-label>
  <input type="text" matInput [matAutocomplete]="autoOutlet">
  <mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngFor="let option of outletFilterOptions | async" [value]="option.id">
      {{ option.name }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

这样设置后,当你选中某个门店选项时,输入框里会显示getValue返回的门店名称,而不是直接显示id,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Sriram Jayaraman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:22:01