You can use the libphonenumber-js library for accurate international formatting.
Phone Number Formatting Pipe with libphonenumber-js
1. Install the Library
npm install libphonenumber-js
2. Create the Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { parsePhoneNumberFromString } from 'libphonenumber-js';
@Pipe({
name: 'phoneFormat'
})
export class PhoneFormatPipe implements PipeTransform {
transform(phoneNumber: string, locale: string = 'US'): string {
if (!phoneNumber) return '';
const parsedNumber = parsePhoneNumberFromString(phoneNumber, locale.toUpperCase());
return parsedNumber ? parsedNumber.formatInternational() : phoneNumber;
}
}
3. Usage in Template
<p>{{ '+14155552671' | phoneFormat:'US' }}</p>
<!-- Output: +1 415 555 2671 -->
<p>{{ '919876543210' | phoneFormat:'IN' }}</p>
<!-- Output: +91 98765 43210 -->