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

Angular 14中ngx-mat-intl-tel-input报错及切换国家码清值问题

Angular 14 中使用 ngx-mat-intl-tel-input 实现手机号验证及国家码切换清空功能

一、解决导入错误

出现"ngx-mat-intl-tel-input" 没有导出成员'NgxMatIntlTelInputModule'错误,核心原因是安装的库版本与Angular 14不兼容,需安装适配版本:

npm install ngx-mat-intl-tel-input@6.0.1 --save

安装完成后,在对应模块(如AppModule或业务模块)中正确导入:

import { NgxMatIntlTelInputModule } from 'ngx-mat-intl-tel-input';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
  imports: [
    // 其他必要模块
    ReactiveFormsModule,
    MatFormFieldModule,
    NgxMatIntlTelInputModule
  ]
})
export class AppModule { }

二、实现带国家码的手机号验证及清空功能

1. 组件逻辑代码

import { Component } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { CountryISO } from 'ngx-mat-intl-tel-input';

@Component({
  selector: 'app-phone-input',
  templateUrl: './phone-input.component.html'
})
export class PhoneInputComponent {
  myForm = this.fb.group({
    name: 'User',
    phone: new FormControl('', [Validators.required])
  });

  // 设置优先显示的国家
  preferredCountries: CountryISO[] = [CountryISO.India, CountryISO.UnitedStates];

  constructor(private fb: FormBuilder) { }

  // 切换国家码时清空手机号
  onCountryChange() {
    this.myForm.get('phone')?.setValue('');
  }
}

2. 模板代码

<mat-form-field appearance="outline">
  <ngx-mat-intl-tel-input
    [preferredCountries]="preferredCountries"
    [enablePlaceholder]="true"
    [enableSearch]="true"
    formControlName="phone"
    name="phone"
    #phone
    (countryChange)="onCountryChange()"
  >
  </ngx-mat-intl-tel-input>
</mat-form-field>

<!-- 验证错误提示 -->
<div *ngIf="myForm.get('phone')?.invalid && (myForm.get('phone')?.dirty || myForm.get('phone')?.touched)">
  <span *ngIf="myForm.get('phone')?.errors?.['required']">手机号不能为空</span>
  <span *ngIf="myForm.get('phone')?.errors?.['validatePhoneNumber']">请输入符合所选国家格式的有效手机号</span>
</div>

三、关键说明

  • 手机号验证:库自带格式校验,当输入不符合当前选中国家的手机号规则时,表单控件会自动添加validatePhoneNumber错误,结合Validators.required即可实现完整验证逻辑。
  • 国家码切换清空:通过监听组件的countryChange事件,在回调中重置手机号表单控件的值即可实现需求。

内容的提问来源于stack exchange,提问作者Abhinay kumar Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:05:02