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

Angular中mat-autocomplete特殊字符移除功能失效求助

问题:为mat-autocomplete添加移除特殊字符功能失效

我是一名初级Web开发者,此前为普通输入框实现的移除特殊字符功能运行正常:

已正常运行的输入框实现

HTML代码

<input id="street{{sid}}" 
       name="street{{sid}}" 
       type="text" 
       placeholder="" 
       class="form-control"
       [(ngModel)]="adres.street" 
       #street="ngModel" 
       required="" 
       (keydown)="this.removeSpecialCharactersFromStreet($event)"
       (keyup)="this.removeSpecialCharactersFromStreet($event)"
       capitalize-first="true">

TS代码

removeSpecialCharactersFromStreet(event) {
  this.adres.street = event.target.value.replace(/[&\/\\#,+()$~%.\]'"*?<>{}@^&=;'"]_!\[]/g, '');
}

现在需要为mat-autocomplete组件添加类似的移除特殊字符功能,编写的代码无法生效,请求解决:

失效的mat-autocomplete实现代码

TS代码

removeSpecialCharactersFromCity(event) {
  this.adres.city = event.target.value.replace(/[&\/\\#,+()$~%.\]'"*?<>{}@^&=;'"]_!\[]/g, '');
}

HTML代码

<mat-autocomplete 
       autoActiveFirstOption 
       #auto="matAutocomplete"
       (keydown)="this.removeSpecialCharactersFromCity($event)" 
       (keyup)="this.removeSpecialCharactersFromCity($event)">
  <mat-option *ngFor="let option of cityFilteredOptions" 
              [value]="option"
              (keydown)="this.removeSpecialCharactersFromCity($event)" 
              (keyup)="this.removeSpecialCharactersFromCity($event)">
    {{option}}
  </mat-option>
</mat-autocomplete>

解决方案

问题核心:mat-autocomplete和mat-option不是输入控件,绑定在它们身上的键盘事件,其event.target不会指向用户输入的输入框,自然无法获取和修改输入值。正确做法是把事件绑定到与mat-autocomplete关联的<input>元素上。

修正后的代码示例

关联的Input元素(关键修改)

<!-- 这个是和mat-autocomplete绑定的输入框,事件要绑在这里 -->
<input type="text" 
       [(ngModel)]="adres.city"
       [matAutocomplete]="auto"
       <!-- 用input事件覆盖所有输入场景,比keydown+keyup更高效 -->
       (input)="removeSpecialCharactersFromCity($event)">

mat-autocomplete部分(无需绑定事件)

<mat-autocomplete 
       autoActiveFirstOption 
       #auto="matAutocomplete">
  <mat-option *ngFor="let option of cityFilteredOptions" 
              [value]="option">
    {{option}}
  </mat-option>
</mat-autocomplete>

优化后的TS代码

removeSpecialCharactersFromCity(event) {
  // 简化正则,去掉重复的字符(原正则里重复了&和")
  const cleanedValue = event.target.value.replace(/[&\/\\#,+()$~%.'":*?<>{}@^=_![]]/g, '');
  this.adres.city = cleanedValue;
  
  // 如果需要实时过滤下拉选项,这里可以手动触发过滤逻辑
  // 比如:this.cityFilteredOptions = this.filterCities(cleanedValue);
}

额外说明

  • 使用input事件替代keydown+keyup:能覆盖键盘输入、粘贴、输入法输入等所有修改输入框内容的场景,更全面高效。
  • 下拉选项无需绑定事件:用户输入操作都在关联的input中完成,选项仅用于展示和选择,不需要处理输入过滤。
  • 正则优化:原正则存在重复的匹配字符(如&和"出现两次),简化后不影响功能且减少匹配开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:43