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

标签 angular npm

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

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

  • 使用用户在其他地区提供的国家代码
    表格或
  • 如果未提供上述内容,则使用用户 IP 的国家代码
    地址

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

    关于如何实现这一点的任何想法,除了将默认国家的期望值动态注入(inject)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];
        }
    

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

    最佳答案

    如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> 
    

    关于angular - 如何使用 ngx-intl-tel-input 选择默认国家/地区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043329/

    相关文章:

    javascript - 如何在编译时动态导入js文件作为browserify的输入?

    node.js - jenkins build 上私有(private) repo 的 NPM 身份验证错误

    typescript - KotlinJS 生成的 npm 链接包

    git - 如何向我的 package.json 添加非 npm 依赖项?

    Mat-Menu 上 Angular-Material 的 Angular Testing

    angular - 如何从 ngrx 商店中获取值(value)到我的模板中?

    angular - 多指令选择器 - 查找模板中使用了哪个选择器

    Angular - 如何从 ngFor 中删除元素

    Angular 错误 this.method 不是函数

    npm - Gulp(泵,运行序列) "task completion callback called too many times"