我在 Angular 项目中使用
ngx-intl-tel-input
库来处理电话号码输入字段。我已经为电话号码字段创建了一个可重用组件,并且将一个 FormControl 从父组件传递给它。
这是我的代码:
组件.ts
import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { CountryISO, PhoneNumberFormat, SearchCountryField } from 'ngx-intl-tel-input';
@Component({
selector: 'app-new-phone-no-field-v1',
templateUrl: './new-phone-no-field-v1.component.html',
styleUrl: './new-phone-no-field-v1.component.css'
})
export class NewPhoneNoFieldV1Component {
@Input() control!: FormControl;
@Input() separateDialCode: boolean = false;
@Input() maxLength: number = 15;
@Input() phoneValidation: boolean = true;
preferredCountries: CountryISO[] = [
CountryISO.UnitedStates,
CountryISO.UnitedKingdom,
CountryISO.India,
CountryISO.Australia,
CountryISO.Philippines,
CountryISO.Thailand,
CountryISO.SouthAfrica,
CountryISO.Panama,
CountryISO.Mexico,
CountryISO.Indonesia,
CountryISO.Canada,
CountryISO.DominicanRepublic,
];
searchCountryField: SearchCountryField[] = [
SearchCountryField.Iso2,
SearchCountryField.Name
];
phoneNumberFormat: PhoneNumberFormat = PhoneNumberFormat.National;
selectedCountryISO: CountryISO = CountryISO.UnitedStates;
}
组件.html
<div class="intl-tel-input-wrapper">
<ngx-intl-tel-input
[cssClass]="'custom'"
[onlyCountries]="preferredCountries"
[enableAutoCountrySelect]="true"
[enablePlaceholder]="true"
[searchCountryFlag]="true"
[searchCountryField]="searchCountryField"
[selectFirstCountry]="false"
[selectedCountryISO]="selectedCountryISO"
[maxLength]="maxLength"
[phoneValidation]="phoneValidation"
[separateDialCode]="true"
[numberFormat]="phoneNumberFormat"
name="phone"
[formControl]="control">
</ngx-intl-tel-input>
<div *ngIf="control.touched && control.invalid" class="error-messages">
<div *ngIf="control.errors?.required">Phone number is required.</div>
<div *ngIf="!control.errors?.validatePhoneNumber?.valid">Invalid phone number.</div>
</div>
</div>
Parent.component.html
<app-new-phone-no-field-v1
[control]="$any(userForm.get('phone'))"
[separateDialCode]="true">
</app-new-phone-no-field-v1>
<div class="error error-msg">
<div *ngIf="f.phone.errors?.required">
Phone Number is required.
</div>
<div *ngIf="f.phone.errors?.pattern">
Phone Number is invalid.
</div>
</div>
API数据: API 以以下格式返回电话号码:
+919876543210
。我正在使用以下方法将此数据修补到表单中:
this.userForm.patchValue({ phone: data.phone });
问题:
在 UI 上,国家/地区代码出现两次:一次在拨号代码中 下拉菜单,然后再次在电话号码字段中。示例:+91 出现在 下拉菜单和 +919876543210 出现在输入字段中。
电话号码不会根据所选内容自动格式化 国家。示例:当我选择美国作为国家/地区时,它没有 将数字格式设置为 (201)-555-1234。
尝试:
ngx-intl-tel-input
配置与文档相符。我该如何解决这些问题,以便:
尝试将 PhoneNumberFormat 设置为
E164
。此外,有效的 stackblitz 将有助于调试并提供快速解决方案。