如何使用 ngx-intl-tel-input 选择默认国家/地区

sth*_*mas 6 npm angular

我正在使用ngx-intl-tel-input以便在我的Angular 7项目中拥有国际电话号码字段。

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

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

  • 如果未提供上述内容,则使用用户 IP 地址的国家代码

根据此包的文档,我没有看到设置默认国家/地区的方法,只有一种为下拉列表设置首选国家/地区并自动选择该数组中的第一个国家/地区的方法

除了将默认国家/地区的所需值动态注入数组的第一个索引的明显解决方法之外,对如何实现此目的还有什么想法吗preferredCountries

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

    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];
    }
Run Code Online (Sandbox Code Playgroud)

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

ala*_*bid 5

如 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> 
Run Code Online (Sandbox Code Playgroud)