I’ve built a more complex setup for masking phone numbers considering a chose country flag next to an input:
<ion-input
label="Phone"
type="number"
[maskito]="phoneMaskObs$ | async"
[maskitoElement]="maskPredicate"
labelPlacement="floating"
formControlName="phone"
>
<ion-select
aria-label="Country"
[value]="selectedValue.value"
interface="alert"
(ionChange)="setPhoneMask($event)"
>
<ion-select-option
[value]="country.value"
*ngFor="let country of countryListIcons"
>{{ country.name }}</ion-select-option
>
</ion-select>
</ion-input>
====== TS file ======
private phoneMask$: BehaviorSubject<MaskitoOptions> = new BehaviorSubject(
this.phoneMaskService.getMaskByCountryCode('RO')
);
public readonly phoneMaskObs$ = this.phoneMask$.asObservable();
protected setPhoneMask(
event: IonSelectCustomEvent<SelectChangeEventDetail<any>>
): void {
const countryCode = event.detail.value;
this.phoneMask$.next(
this.phoneMaskService.getMaskByCountryCode(countryCode)
);
}
protected readonly maskPredicate: MaskitoElementPredicate = async (el) =>
(el as HTMLIonInputElement).getInputElement();
===== phone mask service ====
public getMaskByCountryCode(countryCode: string): MaskitoOptions {
if (!countryCode) return this.phoneMaskList[0].mask;
const mask = this.phoneMaskList.find(
(m) => m.countryCode === countryCode
)?.mask;
if (!mask) return this.phoneMaskList[0].mask;
return mask;
}
public matchAndGetMaskByPhoneNumber(phoneNumber: string): Country | null {
const defaultCountry = countryListIcons.find((c) => c.value === 'RO');
if (!phoneNumber) return defaultCountry;
const countryPhonePrefix = phoneNumber.substring(0, 3);
const countryCode = this.phoneMaskList.find((m) => {
const mask = m.mask.mask as string[];
const maskPrefix = mask.slice(0, 3).join('');
return maskPrefix === countryPhonePrefix;
});
if (!countryCode) return defaultCountry;
return countryListIcons.find(
(c) => c.value === countryCode?.countryCode
);
}
===== the static lists of country codes and according masks ======
export const countryListIcons: Array<Country> = [
{ name: '🇷🇴', value: 'RO' },
{ name: '🇫🇷', value: 'FR' },
{ name: '🇬🇧', value: 'GB' },
{ name: '🇪🇸', value: 'ES' },
{ name: '🇳🇱', value: 'NL' },
{ name: '🇺🇦', value: 'UA' },
{ name: '🇷🇺', value: 'RU' },
{ name: '🇵🇱', value: 'PL' },
{ name: '🇮🇹', value: 'IT' },
.....
private readonly phoneMaskList: Array<{
countryCode: string;
mask: MaskitoOptions;
}> = [
{
countryCode: countryListIcons.find((c) => c.value === 'RO').value,
mask: {
mask: [
'+',
'4',
'0',
' ',
'(',
/\d/,
/\d/,
/\d/,
')',
' ',
/\d/,
/\d/,
/\d/,
'-',
/\d/,
/\d/,
/\d/,
],
},
},
{
countryCode: countryListIcons.find((c) => c.value === 'FR').value,
mask: {
mask: [
'+',
'3',
'3',
' ',
/\d/,
/\d/,
' ',
/\d/,
/\d/,
' ',
/\d/,
/\d/,
' ',
/\d/,
/\d/,
],
},
},
........