Angular与Ionic中实现支持输入筛选的国家码下拉选择功能
国家码搜索筛选功能改造实现
改造思路
完全复用现有代码逻辑,只在国家码下拉弹层增加顶部搜索输入框,新增本地列表过滤逻辑,不引入第三方依赖,和现有交互逻辑完全兼容。
具体代码修改
1. 组件TS逻辑调整
不需要改动原有已写好的手机号校验、选择交互逻辑,在现有组件类中补充以下变量与方法:
// 搜索输入绑定值 searchTerm = ''; // 过滤后的展示用国家码列表 filteredCountries: any[] = []; // 弹层打开方法补充状态重置逻辑 openSelect = () => { this.toggleSelect = !this.toggleSelect; // 每次打开弹层时重置筛选状态,避免上次关闭的残留搜索词 if (this.toggleSelect) { this.searchTerm = ''; this.filterCountries(); } }; // 国家码列表过滤方法 filterCountries() { const term = this.searchTerm.trim().toLowerCase(); // 搜索词为空时展示全量国家码列表 if (!term) { this.filteredCountries = [...this.countrycode]; return; } // 支持双维度匹配:国家名称、拨号区号 this.filteredCountries = this.countrycode.filter(item => { const matchName = item.name.toLowerCase().includes(term); // 去掉区号前面的+号,直接匹配数字,用户输86就能搜到+86 const matchCode = item.dialcode.replace('+', '').includes(term); return matchName || matchCode; }); } // 原有选择国家码的方法补充状态重置 selectPhoneCode = (ccode) => { this.selectedCode = ccode; this.toggleSelect = false; this.updateprofile.MobilePhone = CommonConstants.STRING_EMPTY; // 选完后清空搜索状态 this.searchTerm = ''; this.filterCountries(); };
补充:如果组件存在
ngOnInit生命周期方法,需要在方法内给filteredCountries做初始赋值,避免首次打开弹层时列表空白:ngOnInit() { this.filteredCountries = [...this.countrycode]; }
2. HTML模板调整
在原有的国家码下拉弹层顶部加搜索输入框,把原来循环遍历全量国家码的部分改成遍历过滤后的列表,同时增加空结果提示:
<div class="phone_picker"> <button type="button" (click)="openSelect()">{{ selectedCode }}</button> <div class="country_picker" *ngIf="toggleSelect"> <!-- 新增:顶部搜索输入区 --> <div class="cc_search_wrapper" style="padding: 8px; border-bottom: 1px solid #eee;"> <ion-input [(ngModel)]="searchTerm" (ionInput)="filterCountries()" placeholder="输入国家名或区号搜索" [clearOnEdit]="true" ></ion-input> </div> <!-- 原有列表渲染,把遍历源从countrycode改成filteredCountries --> <div class="c_list ion-activatable ripple-parent" *ngFor="let c of filteredCountries" (click)="selectPhoneCode(c.dialcode)" > <div class="c_box"> <img src="{{ 'assets' }}" alt="..."/> <span>{{ c.name }}</span> </div> </div> <!-- 新增:无匹配结果提示 --> <div *ngIf="filteredCountries.length === 0" style="padding: 16px; text-align: center; color: #999;"> 未找到匹配的国家/地区码 </div> </div> <ion-input appIntegerInput type="tel" (keyup)="numberOnlyValidation($event)" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" [(ngModel)]="updateprofile.MobilePhone" [ngModelOptions]="{ standalone: true }" class="phone_input" placeholder="Phone number" minlength="8" maxlength="12" inputmode="numeric" pattern="[0-9]*" ></ion-input> </div>
体验说明
- 匹配逻辑同时支持国家名称、数字区号搜索:用户不管输入国家名类的文本,还是直接输区号数字,都能快速定位到对应选项,不用再全列表滚动查找
- 弹层打开、选择完成两个时机都会重置搜索状态,不会出现上次筛选的内容残留到下次打开的情况
- 没有额外加载依赖,完全基于现有Angular双向绑定、Ionic原生输入组件实现,和原有手机号校验逻辑完全兼容,不会出现交互冲突
内容的提问来源于stack exchange,提问作者Titus
相关产品推荐
相关产品推荐

