如何在ngx-intl-tel-input中按国家代码搜索或禁止搜索框输入数字?
ngx-intl-tel-input 搜索框问题解决方案
问题背景
使用ngx-intl-tel-input组件实现手机号输入时,国家搜索下拉框仅支持按国家名称搜索,输入如+231这类国家代码时无响应,需优化为以下两种效果之一:
- 禁止搜索框输入数字
- 支持按国家代码搜索
方案一:禁止搜索框输入数字
通过监听搜索框输入事件,过滤所有数字字符:
- 组件类中引入依赖并获取搜索框元素:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-phone-input', templateUrl: './phone-input.component.html' }) export class PhoneInputComponent implements AfterViewInit { @ViewChild('telInput') telInput!: ElementRef; ngAfterViewInit(): void { const searchInput = this.telInput.nativeElement.querySelector('.search-box input'); if (searchInput) { searchInput.addEventListener('input', (e: InputEvent) => { const target = e.target as HTMLInputElement; // 移除输入中的所有数字 target.value = target.value.replace(/\d/g, ''); }); } } }
- 模板中添加组件引用:
<ngx-intl-tel-input #telInput></ngx-intl-tel-input>
方案二:支持按国家代码搜索
自定义过滤逻辑,让搜索关键词同时匹配国家名称和国家代码(兼容带+和不带+的输入):
- 组件类中定义自定义过滤函数:
import { Component } from '@angular/core'; import { SearchCountryField } from 'ngx-intl-tel-input'; @Component({ selector: 'app-phone-input', templateUrl: './phone-input.component.html' }) export class PhoneInputComponent { searchFields = [SearchCountryField.name, SearchCountryField.dialCode]; // 自定义过滤规则:匹配名称或去掉+的代码 filterCountry(country: any, term: string): boolean { const cleanTerm = term.toLowerCase().replace('+', ''); return country.name.toLowerCase().includes(cleanTerm) || country.dialCode.replace('+', '').includes(cleanTerm); } }
- 模板中绑定过滤函数和搜索字段:
<ngx-intl-tel-input [searchCountryField]="searchFields" [customCountryFilter]="filterCountry" ></ngx-intl-tel-input>
配置完成后,输入231或+231均可匹配到对应国家,同时保留按名称搜索的功能。
内容的提问来源于stack exchange,提问作者Cpt Kitkat
相关产品推荐
相关产品推荐

