Angular Material Autocomplete 选中时如何获取完整选中对象而非仅name值
问题根因
- 当前
mat-option的绑定值直接设置为option.name字符串,所有选中场景下传递的都是name字段的文本值,无法关联到完整的联赛选项对象 - 原来的
optionSelected事件取值直接传递了$event.option(即MatOption组件实例本身),没有取到实例上绑定的实际value值 - 如果直接把完整对象绑定为mat-option的value,未配置
displayWith会导致输入框直接展示[object Object]的异常
具体修改实现
- 调整
mat-option的值绑定:将原字符串绑定替换为整对象绑定,把完整的ILeague对象作为option的实际存储值 - 给
mat-autocomplete添加displayWith配置,指定选中后输入框仅展示对象的name字段,避免展示原始对象 - 调整过滤方法的参数判断逻辑,兼容用户手动输入的字符串、选中后传入的完整对象两种场景
- 修正选中事件的取值路径,从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
相关产品推荐
相关产品推荐

