Angular Mat Autocomplete选中显示itemDescription及报错解决求助
Angular Mat Autocomplete 问题解决方案
问题1:选中选项后输入框显示item.id而非itemDescription
原因:<mat-option>的[value]绑定了item.id,选中后输入框直接渲染该值。要实现「显示描述、表单可按需存储id/完整对象」的需求,需用displayWith自定义显示逻辑。
解决方法
方案1:绑定整个item对象(推荐,表单值为完整item,提交时提取id即可)
- 组件中添加显示函数:
displayItem(item: any): string { return item ? item.itemDescription : ''; }
- 修改HTML模板,添加
[displayWith]并调整[value]绑定:
<td> <input matInput type="text" [matAutocomplete]="auto" formControlName="item"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayItem"> <mat-option *ngFor="let item of filteredOptions" [value]="item"> {{item.itemDescription}} </mat-option> </mat-autocomplete> </td>
方案2:保持绑定item.id(表单值为id)
- 组件中添加显示函数:
displayItem(id: number): string { if (!id) return ''; const targetItem = this.options.find(item => item.id === id); return targetItem ? targetItem.itemDescription : ''; }
- HTML模板仅添加
[displayWith]:
<td> <input matInput type="text" [matAutocomplete]="auto" formControlName="item"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayItem"> <mat-option *ngFor="let item of filteredOptions" [value]="item.id"> {{item.itemDescription}} </mat-option> </mat-autocomplete> </td>
问题2:选中选项后出现ERROR TypeError: enterData.toLowerCase is not a function
原因:选中选项后,表单控件值变为item.id(数字类型),而filterData中直接调用仅字符串支持的toLowerCase()方法,导致报错。同时需兼容空输入的情况。
解决方法
修改filterData函数,先将输入值转为字符串再处理:
filterData(enterData: any){ const searchText = String(enterData).toLowerCase(); this.filteredOptions = this.options.filter(item => { return item.itemDescription.toLowerCase().includes(searchText); }) }
额外修正点
- Angular生命周期钩子需用驼峰写法
ngOnInit(原代码ngOninit拼写错误,不会执行),同时修正FormArray的控件获取逻辑:
ngOnInit() { // 先调用接口获取选项数据 this.getData(); // 监听FormArray中第一个表单组的item控件值变化 const arrayForm = this.form.get('ArrayForm') as FormArray; arrayForm.at(0).get('item')?.valueChanges.subscribe(response => { this.filterData(response); }); }
- 原代码中直接调用
this.ArrayForm.get('item')有误,因为ArrayForm是FormArray类型,需先通过索引获取对应表单组,再提取目标控件。
内容的提问来源于stack exchange,提问作者Alluring
相关产品推荐
相关产品推荐

