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

如何在Angular 14中使用ngx-intl-tel-input实现手机号验证与编辑回显

Angular 14 结合 ngx-intl-tel-input 实现带区号手机号验证及编辑场景处理

1. 安装依赖

首先安装库及所需依赖:

npm install ngx-intl-tel-input @angular/cdk --save

2. 导入模块

在你的功能模块(如AppModule或自定义业务模块)中导入所需模块:

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { NgxIntlTelInputModule } from 'ngx-intl-tel-input';

@NgModule({
  imports: [
    ReactiveFormsModule,
    NgxIntlTelInputModule
  ]
})
export class YourModule { }

3. 组件中配置响应式表单

在组件内初始化表单,添加手机号验证规则:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PhoneNumberValidator } from 'ngx-intl-tel-input';

@Component({
  selector: 'app-phone-input',
  templateUrl: './phone-input.component.html',
  styleUrls: ['./phone-input.component.css']
})
export class PhoneInputComponent implements OnInit {
  phoneForm!: FormGroup;
  // 可选:设置优先显示的国家列表,按国家代码缩写配置
  preferredCountries: string[] = ['US', 'GB', 'IN'];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.initPhoneForm();
  }

  private initPhoneForm(): void {
    this.phoneForm = this.fb.group({
      phone: ['', [
        Validators.required,
        PhoneNumberValidator.validCountryPhone
      ]]
    });
  }
}

4. 模板实现及区号切换处理

在模板中添加组件,并绑定区号切换事件以清空手机号:

<form [formGroup]="phoneForm">
  <ngx-intl-tel-input
    formControlName="phone"
    [preferredCountries]="preferredCountries"
    [enableAutoCountrySelect]="false"
    [enablePlaceholder]="true"
    [searchCountryFlag]="true"
    [searchCountryField]="['name', 'dialCode']"
    [selectFirstCountry]="false"
    (countryChange)="clearPhoneNumber()"
  ></ngx-intl-tel-input>

  <!-- 错误提示 -->
  <div *ngIf="phoneForm.get('phone')?.invalid && phoneForm.get('phone')?.touched">
    <span *ngIf="phoneForm.get('phone')?.errors?.['required']">手机号不能为空</span>
    <span *ngIf="phoneForm.get('phone')?.errors?.['validCountryPhone']">请输入符合格式的手机号</span>
  </div>
</form>

在组件中实现清空方法:

clearPhoneNumber(): void {
  this.phoneForm.get('phone')?.setValue('');
}

5. 编辑场景下的patchValue赋值

编辑场景中,需要传入包含number(手机号)和countryCode(国家代码)的对象进行赋值:

情况1:已有拆分好的手机号和国家代码

// 假设从后端获取的用户手机号数据
const userPhoneInfo = {
  number: '1234567890',
  countryCode: 'US'
};

// 使用patchValue赋值
this.phoneForm.patchValue({
  phone: userPhoneInfo
});

情况2:后端返回完整带区号的手机号

如果后端返回的是如+11234567890这类完整号码,可借助libphonenumber-js(库内置依赖)解析后赋值:

import { parsePhoneNumberFromString } from 'libphonenumber-js';

const fullPhoneNumber = '+11234567890';
const parsedNumber = parsePhoneNumberFromString(fullPhoneNumber);

if (parsedNumber) {
  this.phoneForm.patchValue({
    phone: {
      number: parsedNumber.nationalNumber,
      countryCode: parsedNumber.country
    }
  });
}

内容的提问来源于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 04:26:26