【问题标题】:How to select a default country with ngx-intl-tel-input如何使用 ngx-intl-tel-input 选择默认国家/地区
【发布时间】:2019-09-26 08:09:46
【问题描述】:

我使用ngx-intl-tel-input 是为了在我的Angular 7 项目中拥有一个国际电话号码字段。

我希望能够通过以下任一方式设置下拉菜单的默认国家/地区(以及相应的占位符):

  • 使用用户在其他地区提供的国家代码 表格或,

  • 如果上面没有提供,使用用户IP的国家代码 地址

根据此软件包的文档,我看不到设置默认国家/地区的方法,只能为下拉菜单设置首选国家/地区并自动选择该数组中的第一个国家/地区

除了将默认国家/地区的期望值动态注入preferredCountries数组的第一个索引的明显解决方法之外,关于如何实现这一点的任何想法?

** 更新 ** 我不想为此使用preferredCountries 数组的原因是因为我需要它来动态更改。由于 ngx-intl-tel-input 组件通过实现OnInit 来设置preferredCountries 中列出的国家/地区,因此我无法找到一种方法来更改下拉国家/地区。

    ngOnInit() {

    this.fetchCountryData();

    if (this.preferredCountries.length) {
        this.preferredCountries.forEach(iso2 => {
            const preferredCountry = this.allCountries.filter((c) => {
                return c.iso2 === iso2;
            });

            this.preferredCountriesInDropDown.push(preferredCountry[0]);
        });
    }
    if (this.onlyCountries.length) {
        this.allCountries = this.allCountries.filter(c => this.onlyCountries.includes(c.iso2));
    }
    if (this.preferredCountriesInDropDown.length) {
        this.selectedCountry = this.preferredCountriesInDropDown[0];
    } else {
        this.selectedCountry = this.allCountries[0];
    }

如果您知道解决此问题的方法,我很乐意使用 preferredCountries 数组来实现我想要的行为,但是以上是目前阻止我这样做的原因。

【问题讨论】:

  • 找到解决方案了吗?

标签: angular npm


【解决方案1】:

如github上所示,你可以设置[preferredCountries]="[yourDefaultCountryCode]",例如这个会显示英国:

<ngx-intl-tel-input 
    [cssClass]="'custom'" 
    [preferredCountries]="['gb']" <!-- THIS ONE -->
    [enablePlaceholder]="true"
    [enableAutoCountrySelect]="true"
    name="phone" 
    formControlName="phone"></ngx-intl-tel-input> 

【讨论】:

  • 感谢您的及时反馈,但这正是我试图避免的解决方法。相反,我问是否有任何替代解决方案,其中不包括篡改首选国家/地区数组。
  • 我认为这是正确的做法,为什么不呢?
【解决方案2】:

您可以使用 ng2-tel-input 它适用于 angular 2+ enter link description here

并将其用于 Ex 将埃及设置为默认国家 [ng2TelInputOptions]="{initialCountry: 'eg'}", "eg" -> "Egypt"。

<input [(ngModel)]="Phone_Number" required type="tel" ng2TelInput (hasError)="hasError($event)" (ng2Tel[][1]Output)="getNumber($event)" (intlTelInputObject)="telInputObject($event)" (countryChange)="onCountryChange($event)" [ng2TelInputOptions]="{initialCountry: 'eg'}"/>

【讨论】:

    【解决方案3】:

    在 TS 中:

    import { CountryISO, SearchCountryField } from 'ngx-intl-tel-input';
    CountryISO = CountryISO;
    

    在 HTML 中:

    <ngx-intl-tel-input [selectedCountryISO]="CountryISO.India" ...> </ngx-intl-tel-input>
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2023-01-31
      • 2020-03-15
      • 2021-12-02
      • 2020-01-05
      • 2019-09-10
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多