如何实现Angular Material Autocomplete过滤非数值字符功能?
实现Angular Material Autocomplete忽略非数值字符的筛选功能
需求说明
需要为Angular Material Autocomplete组件实现输入联想时忽略非数值字符的功能:例如下拉选项包含123/12R34、123/13R45,当输入12312时应能筛选出123/12R34;但当前输入123后,因选项中包含“/”字符,搜索就停止匹配了。现有代码如下:
<ng-container *ngIf="question.questionType === 'AUTOCOMPLETE'"> <mat-form-field> <input matInput name="{{ question.id }}" [ngClass]="question.cssClass" [ngModel]="answers[question.id]?.answer" (ngModelChange)=" setFilteredOptionsbyQuestion(question, $event) && (answers[question.id] = answers[question.id] ? answers[question.id] : {}) && (answers[question.id].answer = $event) " (keypress)="onKeyPress($event)" type="text" [matAutocomplete]="auto" /> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of filteredOptions[question.id]" value="{{ option.value ? option.value : option.label }}" >{{ option.label }}</mat-option > </mat-autocomplete> </mat-form-field> </ng-container>
setFilteredOptions = () => { this.questions.forEach(q => { if (q.optionGroup && q.questionType === 'AUTOCOMPLETE') { this.filteredOptions[q.id] = this.groupOptions[q.optionGroup] ? this.groupOptions[q.optionGroup] : []; } }); };
解决方案
1. 添加移除非数值字符的工具函数
在组件类中新增一个工具函数,用于剥离字符串中的所有非数字字符:
stripNonNumeric(str: string): string { // 正则匹配所有非0-9的字符并替换为空 return str.replace(/[^0-9]/g, ''); }
2. 修改筛选逻辑方法setFilteredOptionsbyQuestion
更新筛选方法,对用户输入和选项标签都进行非数值字符剥离后,再执行包含匹配:
setFilteredOptionsbyQuestion(question: any, inputValue: string): void { // 若当前问题无选项组,直接返回 if (!question.optionGroup) return; // 获取该问题对应的原始选项列表 const originalOptions = this.groupOptions[question.optionGroup] || []; // 清理用户输入,只保留数字 const cleanedInput = this.stripNonNumeric(inputValue); // 筛选出清理后的标签包含清理后输入的选项 this.filteredOptions[question.id] = originalOptions.filter(option => { const cleanedLabel = this.stripNonNumeric(option.label); return cleanedLabel.includes(cleanedInput); }); }
3. 保留初始选项初始化逻辑
原有的setFilteredOptions方法无需修改,它负责在组件初始化时为每个自动完成控件加载完整的选项列表。
逻辑说明
通过对用户输入和选项标签同时进行非数值字符剥离,只保留数字部分进行匹配,即可忽略选项中的/、R等非数字字符的影响。比如输入12312时,清理后还是12312;选项123/12R34清理后是1231234,包含12312,因此会被筛选出来。
内容的提问来源于stack exchange,提问作者codeflinger
相关产品推荐
相关产品推荐

