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

Angular中intl-tel-input设置相同国家时触发countrychange事件的方法

解决方案

intl-tel-input 原生的countrychange事件仅在选中国家发生实际变更时触发,对当前已选中的国家重复调用setCountry默认不会触发事件,无需使用先切换其他国家再切回的 hack 方案,可通过以下两种方式实现需求:

方法1:手动派发countrychange事件

设置国家后主动触发事件,即可复用已绑定的监听逻辑:

ngAfterViewInit(): void {
  this.iti = intlTelInput(this.input.input.nativeElement, {
    utilsScript: '../../assets/js/phone-utils.js',
    preferredCountries: this.preferredCountries
  })
  this.input.nativeElement.addEventListener('countrychange', () => {
    this.countryCodeControl.setValue(this.iti.getSelectedCountryData().dialCode)
  })
  // 初始化设置国家后手动触发事件
  this.iti.setCountry('de')
  this.input.nativeElement.dispatchEvent(new Event('countrychange'))
}

方法2:抽离公共逻辑直接调用(更推荐)

将更新区号的逻辑抽为独立方法,初始化时直接调用,无需依赖事件触发,逻辑更清晰:

ngAfterViewInit(): void {
  this.iti = intlTelInput(this.input.input.nativeElement, {
    utilsScript: '../../assets/js/phone-utils.js',
    preferredCountries: this.preferredCountries
  })
  this.input.nativeElement.addEventListener('countrychange', () => this.updateCountryCode())
  // 初始化直接调用更新逻辑
  this.iti.setCountry('de')
  this.updateCountryCode()
}

// 抽离的公共更新方法
private updateCountryCode(): void {
  this.countryCodeControl.setValue(this.iti.getSelectedCountryData().dialCode)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:36:05