You need to enable JavaScript to run this app. Angular Material Autocomplete 选中时如何获取完整选中对象而非仅name值
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material Autocomplete 选中时如何获取完整选中对象而非仅name值

问题根因

  • 当前mat-option的绑定值直接设置为option.name字符串,所有选中场景下传递的都是name字段的文本值,无法关联到完整的联赛选项对象
  • 原来的optionSelected事件取值直接传递了$event.option(即MatOption组件实例本身),没有取到实例上绑定的实际value值
  • 如果直接把完整对象绑定为mat-option的value,未配置displayWith会导致输入框直接展示[object Object]的异常

具体修改实现

  1. 调整mat-option的值绑定:将原字符串绑定替换为整对象绑定,把完整的ILeague对象作为option的实际存储值
  2. 给mat-autocomplete添加displayWith配置,指定选中后输入框仅展示对象的name字段,避免展示原始对象
  3. 调整过滤方法的参数判断逻辑,兼容用户手动输入的字符串、选中后传入的完整对象两种场景
  4. 修正选中事件的取值路径,从MatOption实例上取实际绑定的value值,即可拿到完整的选项信息

修改后的模板代码

<form class="example-form">
    <mat-form-field class="example-full-width">
        <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
            [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" 
                          [displayWith]="displayLeagueName"
                          (optionSelected)='selectOption($event.option.value)'>
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
                {{option.name}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
    <router-outlet></router-outlet>
</form>

修改后的组件TS代码

import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { FormControl } from '@angular/forms';

interface ILeague {
  _id: string;
  teams: any[];
  name: string;
  sport: string;
}

export class SearchLeagueComponent implements OnInit {
  constructor(private searchLeagueService: SearchLeagueService) { }
  // 表单控件类型兼容三种状态:空、用户输入的字符串、选中的完整联赛对象
  myControl = new FormControl<ILeague | string | null>(null);
  options: ILeague[] = [
    {
      _id: '',
      teams: [],
      name: '',
      sport: ''
    }
  ];
  filteredOptions: Observable<ILeague[]> | undefined;

  ngOnInit() {
    this.searchLeagueService.getLeaguesList().toPromise().then(data => this.options = data)
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map((value: string | ILeague | null) => this._filter(value))
      );
  }

  // displayWith方法:控制输入框展示的文本内容
  displayLeagueName(league: ILeague | null): string {
    return league ? league.name : '';
  }

  // 选中事件直接接收完整的联赛对象,可自由取任意字段
  selectOption(league: ILeague) {
    console.log('选中的完整联赛对象:', league);
    console.log('联赛id:', league._id);
    console.log('所属运动类型:', league.sport);
  }

  // 过滤逻辑兼容两种输入状态
  private _filter(value: string | ILeague | null): ILeague[] {
    if (!value) return this.options;
    // 区分用户手动输入的字符串、已选中的对象两种取值
    const filterValue = typeof value === 'string' 
      ? value.toLowerCase() 
      : value.name.toLowerCase();
    return this.options.filter(option => option.name.toLowerCase().includes(filterValue));
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 19:06:08