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

Angular的mat-autocomplete如何同时显示对象的瑞典语和英语两个属性值

解决方案

你只需要修改两处代码即可实现需求:

1. 修改模板中的下拉选项渲染逻辑

在<mat-option>标签内同时输出瑞典语和英语两个字段,你可以根据需求调整两个字段的分隔样式,以下是示例:

<mat-form-field class="columnTranslator" appearance="outline">
  <mat-label class="inputTranslator">Enter text</mat-label>
  <input
    type="text"
    placeholder="Pick one"
    aria-label="Number"
    matInput
    [formControl]="myControl"
    [matAutocomplete]="auto"/>
  <mat-autocomplete #auto="matAutocomplete" >
    <mat-option
      *ngFor="let option of filteredOptions | async" 
      [value]="option.swedish">
      <!-- 同时展示两个属性,用短横线分隔 -->
      {{ option.swedish }} - {{ option.english }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

修改后下拉选项就会显示为 Stol - Chair、Mus - Mouse 的格式,和你预期的效果一致。

2. (可选)扩展搜索匹配逻辑

当前你的过滤逻辑只匹配瑞典语字段,如果需要支持输入英语也能搜到对应选项,可以修改组件内的filter方法:

filter(val: string): Observable<any[]> {
  const lowerVal = val.toLowerCase();
  return this.searchService.getData().pipe(
    map((response) =>
      response.filter((option: { swedish: string, english: string }) => {
        // 匹配瑞典语开头 或者 英语开头
        return option.swedish.toLowerCase().startsWith(lowerVal) 
          || option.english.toLowerCase().startsWith(lowerVal);
      })
    )
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:04