Member-only story

Formatting Phone Numbers in Angular with a Custom Pipe

Learn_With_Awais
4 min read1 day ago

In any modern web application, displaying user data in a clean, readable format is key. Phone numbers are no exception. In Angular, custom pipes make it easy to transform and format data right within the template. Today, we’re taking a deep dive into a custom PhoneFormatPipe that takes a phone number (as a string or number) and formats it in a more human-readable form.

What Does PhoneFormatPipe Do?

The primary goal of this pipe is to standardize phone number formatting. Rather than allowing various raw inputs that might confuse users or mess up layout, this pipe transforms numbers into a format that includes country codes, area (or city) codes, and properly hyphenated numbers. The pipe also respects input that might already be formatted by returning it as-is when necessary.

The Implementation

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
name: 'phoneFormat',
standalone: true,
})
export class PhoneFormatPipe implements PipeTransform

transform( tel: string | number, usFormat: boolean = true ): string {

if ( !tel ) {
return '';
}

// If the number has anything other than digits (numbers) OR a plus sign at first position after trimming white space - return it as is because user has formatted it himself
if ( /^\+?\d+$/.test(…

--

--

Learn_With_Awais
Learn_With_Awais

Written by Learn_With_Awais

“Angular Developer | Tech Enthusiast | Sharing insights on modern web development, AI tools, and productivity hacks. Let’s build smarter, together! 🚀”

Responses (1)