Mastering Custom Pipes in Angular: 31 Real-world Examples (2024)
Angular provides a powerful “pipes” feature to transform and format data in templates. While Angular includes a variety of built-in pipes…
Mastering Custom Pipes in Angular: 31 Real-world Examples (2024)

Mastering Custom Pipes in Angular 31 Real-world Examples (2023). Photo by Astrit Shuli. Image by storyset on Freepik
Angular provides a powerful “pipes” feature to transform and format data in templates. While Angular includes a variety of built-in pipes, sometimes you may need to create a custom pipe to suit your application requirements.
In this article, we will explore the concept of custom pipes in Angular and walk through 31 real-world examples to demonstrate the practical use.

Build in AI speed — Compose enterprise-grade applications, features, and components
What are Angular Pipes?
Angular pipes are simple functions that allow you to transform and format data directly within templates. They are used by adding a pipe operator (|) in the HTML template. Angular provides several built-in pipes for common tasks like formatting dates, currency, and text transformations. Custom pipes extend this functionality by allowing you to create your data transformation logic.
Creating a Custom Pipe
Before diving into examples, let’s understand how to create a custom pipe in Angular. You can create a custom pipe by implementing the PipeTransform interface and providing the transformation logic in the transform method.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customPipeName'
})
export class CustomPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
// Your transformation logic here
}
}
31 Custom Pipe Examples
- Uppercase First Pipe: This pipe capitalizes the first letter of a string while keeping the rest in lowercase.
- Reverse String Pipe: It reverses the characters of a string, making it useful for creating mirror text effects.
- Filter Array Pipe: Filters an array of objects based on a given property and filter value. This is handy for creating dynamic search functionality.
- Truncate Text Pipe: Shortens text to a specified length and appends an ellipsis if the text exceeds the limit.
- Sort Array Pipe: Sorts an array of objects based on a specified property in ascending or descending order.
- Currency Converter Pipe: Converts a value from one currency to another using a provided exchange rate.
- Phone Number Formatter Pipe: Formats a raw string of numbers into a well-structured phone number format (e.g., (555) 555–5555).
- File Size Pipe: Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
- Markdown To HTML Pipe: Transforms Markdown text into HTML for rendering within your application.
- Time Ago Pipe: Displays a human-friendly representation of a timestamp, indicating how long ago an event occurred (e.g., “3 hours ago” or “yesterday”).
- Percent Change Pipe: Calculates the percentage change between two values and formats it with a plus or minus sign.
- Initials Pipe: Extracts and displays the initials from a full name, useful for user profile displays.
- Strip HTML Tags Pipe: Removes all HTML tags from a given string, ensuring that only plain text is displayed.
- Camel Case To Spaces Pipe: Converts camelCase or PascalCase strings into human-readable sentences with spaces.
- Title Case Pipe: Converts a string to title case, where the first letter of each word is capitalized, and the rest are in lowercase.
- Masked Input Pipe: Formats user input as they type, such as formatting a phone number with parentheses and hyphens as it is entered.
- Pluralize Pipe: Handles pluralization of words based on the count provided. For example, it can change “item” to “items” when the count is greater than one.
- Humanize Duration Pipe: Converts a duration in seconds into a more human-readable format, like “2 hours and 30 minutes.”
- JSON Pretty Print Pipe: Takes a JSON object and pretty-prints it, making it more readable for debugging purposes.
- Password Strength Pipe: Checks the strength of a password and provides feedback on its complexity, like “Weak,” “Medium,” or “Strong.”
- Ordinal Number Pipe: Converts a number into its corresponding ordinal representation (e.g., 1st, 2nd, 3rd, 4th, etc.).
- URLify Pipe: Converts a string into a URL-friendly format, replacing spaces with hyphens and removing special characters.
- Relative Time Pipe: Displays timestamps in a relative format, like “just now,” “a few minutes ago,” or “yesterday.”
- Array Shuffle Pipe: Shuffles the elements of an array, creating a random order for display.
- Color Contrast Pipe: Determines the best text color (black or white) to ensure good contrast against a background color.
- Roman Numeral Pipe: Converts Arabic numerals to Roman numerals and vice versa.
- Sentence Case Pipe: Capitalizes the first letter of each sentence in a block of text.
- CSV To Array Pipe: Parses a CSV (Comma-Separated Values) string into an array for easier data manipulation.
- Slugify Pipe: Converts a string into a URL slug by removing special characters, converting spaces to hyphens, and making it lowercase.
- Random Placeholder Image Pipe: Generates random placeholder images with varying colors and patterns, suitable for mockups and testing.
- Phone Number Mask Pipe: Evaluates the strength of a password and provides feedback, such as weak, medium, or strong, based on predefined criteria.
1. Uppercase First Pipe
This pipe capitalizes the first letter of a string while keeping the rest in lowercase.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'uppercaseFirst' })
export class UppercaseFirstPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
}
}
Usage in an Angular template:
<p>{{ 'hello world' | uppercaseFirst }}</p>
<!-- Output: "Hello world" -->
2. Reverse String Pipe
This pipe reverses the characters of a string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverseString' })
export class ReverseStringPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.split('').reverse().join('');
}
}
Usage in an Angular template:
<p>{{ 'Angular' | reverseString }}</p>
<!-- Output: "ralugnA" -->
3. Filter Array Pipe
Filters an array of objects based on a given property and filter value.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'filterArray' })
export class FilterArrayPipe implements PipeTransform {
transform(items: any[], property: string, filterValue: any): any[] {
if (!items) return [];
return items.filter(item => item[property] === filterValue);
}
}
Usage in an Angular template:
<ul>
<li *ngFor="let item of items | filterArray:'category':'Electronics'">{{ item.name }}</li>
</ul>
4. Truncate Text Pipe
Shortens text to a specified length and appends an ellipsis if the text exceeds the limit.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
transform(text: string, limit: number): string {
if (text.length <= limit) return text;
return text.slice(0, limit) + '...';
}
}
Usage in an Angular template:
<p>{{ 'This is a long text that should be truncated' | truncateText:20 }}</p>
<!-- Output: "This is a long text..." -->
5. Sort Array Pipe
Sorts an array of objects based on a specified property in ascending or descending order.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sortArray' })
export class SortArrayPipe implements PipeTransform {
transform(array: any[], property: string, order: 'asc' | 'desc' = 'asc'): any[] {
if (!array) return [];
return array.sort((a, b) => {
if (order === 'asc') {
return a[property] < b[property] ? -1 : 1;
} else {
return b[property] < a[property] ? -1 : 1;
}
});
}
}
Usage in an Angular template:
<ul>
<li *ngFor="let item of items | sortArray:'price':'asc'">{{ item.name }} - {{ item.price }}</li>
</ul>
6. Currency Converter Pipe
Converts a value from one currency to another using a provided exchange rate.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'currencyConverter' })
export class CurrencyConverterPipe implements PipeTransform {
transform(value: number, exchangeRate: number): number {
if (isNaN(value) || isNaN(exchangeRate)) return value;
return value * exchangeRate;
}
}
Usage in an Angular template:
<p>{{ 100 | currencyConverter:1.2 }}</p>
<!-- Output: 120 -->
7. Phone Number Formatter Pipe
Formats a raw string of numbers into a well-structured phone number format (e.g., (555) 555–5555).
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneNumberFormatter' })
export class PhoneNumberFormatterPipe implements PipeTransform {
transform(value: string): string {
if (!value || value.length !== 10) return value;
return `(${value.slice(0, 3)}) ${value.slice(3, 6)}-${value.slice(6)}`;
}
}
Usage in an Angular template:
<p>{{ '1234567890' | phoneNumberFormatter }}</p>
<!-- Output: "(123) 456-7890" -->
8. File Size Pipe
Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'fileSize' })
export class FileSizePipe implements PipeTransform {
transform(bytes: number): string {
if (isNaN(bytes) || bytes === 0) return '0 Bytes';
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(2))} ${sizes[i]}`;
}
}
Usage in an Angular template:
<p>{{ 1024 | fileSize }}</p>
<!-- Output: "1 KB" -->
9. Markdown To HTML Pipe
Transforms Markdown text into HTML for rendering within your Angular application. To use this pipe, you can employ a library like marked to convert Markdown to HTML.
First, you need to install the marked library:
npm install marked
Then, create the MarkdownToHTMLPipe:
import { Pipe, PipeTransform } from '@angular/core';
import * as marked from 'marked';
@Pipe({ name: 'markdownToHtml' })
export class MarkdownToHTMLPipe implements PipeTransform {
transform(markdown: string): string {
if (!markdown) return '';
return marked(markdown);
}
}
Usage in an Angular template:
<div [innerHtml]="markdownText | markdownToHtml"></div>
<!-- Assuming markdownText contains Markdown content -->
10. Time Ago Pipe
Displays a human-friendly representation of a timestamp, indicating how long ago an event occurred (e.g., “3 hours ago” or “yesterday”).
To implement a TimeAgo pipe, you can use a library like date-fns to calculate the relative time.
First, install the date-fns library:
npm install date-fns
Create the TimeAgoPipe:
import { Pipe, PipeTransform } from '@angular/core';
import { formatDistanceToNow } from 'date-fns';
@Pipe({ name: 'timeAgo' })
export class TimeAgoPipe implements PipeTransform {
transform(timestamp: number | Date): string {
if (!timestamp) return '';
return formatDistanceToNow(timestamp) + ' ago';
}
}
Usage in an Angular template:
<p>{{ someTimestamp | timeAgo }}</p>
<!-- Example: "3 hours ago" or "yesterday" -->
11. Percent Change Pipe
Calculates the percentage change between two values and formats it with a plus or minus sign.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'percentChange' })
export class PercentChangePipe implements PipeTransform {
transform(currentValue: number, previousValue: number): string {
if (isNaN(currentValue) || isNaN(previousValue)) return '';
const change = ((currentValue - previousValue) / Math.abs(previousValue)) * 100;
const sign = change >= 0 ? '+' : '-';
return `${sign}${change.toFixed(2)}%`;
}
}
Usage in an Angular template:
<p>{{ 85 | percentChange:100 }}</p>
<!-- Output: "-15.00%" -->
12. Initials Pipe
Extracts and displays the initials from a full name, useful for user profile displays.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
transform(fullName: string): string {
if (!fullName) return '';
const nameParts = fullName.split(' ');
return nameParts
.map(part => part.charAt(0).toUpperCase())
.join('');
}
}
Usage in an Angular template:
<p>{{ 'John Doe' | initials }}</p>
<!-- Output: "JD" -->
13. Strip HTML Tags Pipe
Removes all HTML tags from a given string, ensuring that only plain text is displayed.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'stripHtmlTags' })
export class StripHTMLTagsPipe implements PipeTransform {
transform(html: string): string {
if (!html) return '';
return html.replace(/<[^>]*>/g, '');
}
}
Usage in an Angular template:
<p>{{ '<p>This is <b>HTML</b> text</p>' | stripHtmlTags }}</p>
<!-- Output: "This is HTML text" -->
14. Camel Case To Spaces Pipe
Converts camelCase or PascalCase strings into human-readable sentences with spaces.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'camelCaseToSpaces' })
export class CamelCaseToSpacesPipe implements PipeTransform {
transform(camelCaseText: string): string {
if (!camelCaseText) return '';
return camelCaseText.replace(/([a-z])([A-Z])/g, '$1 $2');
}
}
Usage in an Angular template:
<p>{{ 'camelCaseExample' | camelCaseToSpaces }}</p>
<!-- Output: "camel Case Example" -->
15. Title Case Pipe
Converts a string to title case, where the first letter of each word is capitalized, and the rest are in lowercase.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'titleCase' })
export class TitleCasePipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
}
Usage in an Angular template:
<p>{{ 'this is a title case example' | titleCase }}</p>
<!-- Output: "This Is A Title Case Example" -->
16. Masked Input Pipe
Formats user input as they type, such as formatting a phone number with parentheses and hyphens as it is entered. Implementing this pipe would involve monitoring and manipulating user input in real time, and the example below demonstrates a simple masking for phone numbers.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'maskedInput' })
export class MaskedInputPipe implements PipeTransform {
transform(input: string, mask: string): string {
if (!input || !mask) return input;
let result = '';
let inputIndex = 0;
for (let i = 0; i < mask.length; i++) {
if (mask[i] === '*') {
result += input[inputIndex] || '';
inputIndex++;
} else {
result += mask[i];
}
}
return result;
}
}
Usage in an Angular template:
<input [ngModel]="'1234567890'" [ngModelOptions]="{updateOn: 'blur'}" [value]="'(***) ***-****' | maskedInput">
<!-- As you type in the input field, it will be formatted like (123) 456-7890 -->
17. Pluralize Pipe
Handles pluralization of words based on the count provided. It can change “item” to “items” when the count is greater than one.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'pluralize' })
export class PluralizePipe implements PipeTransform {
transform(word: string, count: number): string {
if (!word) return '';
if (count === 1) {
return word;
} else {
// Simple rule for adding "s" to make it plural
return word + 's';
}
}
}
Usage in an Angular template:
<p>{{ 1 | pluralize:'item' }}</p>
<!-- Output: "item" -->
<p>{{ 5 | pluralize:'item' }}</p>
<!-- Output: "items" -->
18. Humanize Duration Pipe
Converts a duration in seconds into a more human-readable format, like “2 hours and 30 minutes.”
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'humanizeDuration' })
export class HumanizeDurationPipe implements PipeTransform {
transform(durationInSeconds: number): string {
if (isNaN(durationInSeconds)) return '';
const hours = Math.floor(durationInSeconds / 3600);
const minutes = Math.floor((durationInSeconds % 3600) / 60);
let result = '';
if (hours > 0) {
result += `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
}
if (minutes > 0) {
if (result) result += ' and ';
result += `${minutes} ${minutes === 1 ? 'minute' : 'minutes'}`;
}
return result || '0 minutes';
}
}
Usage in an Angular template:
<p>{{ 7200 | humanizeDuration }}</p>
<!-- Output: "2 hours" -->
<p>{{ 150 | humanizeDuration }}</p>
<!-- Output: "2 hours and 30 minutes" -->
<p>{{ 30 | humanizeDuration }}</p>
<!-- Output: "30 minutes" -->
<p>{{ 0 | humanizeDuration }}</p>
<!-- Output: "0 minutes" -->
19. JSON Pretty Print Pipe
Takes a JSON object and pretty-prints it, making it more readable for debugging purposes. To accomplish this, you can use the JSON.stringify method with the spacing argument.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'jsonPrettyPrint' })
export class JSONPrettyPrintPipe implements PipeTransform {
transform(jsonObject: any): string {
if (!jsonObject) return '';
return JSON.stringify(jsonObject, null, 2); // 2 spaces for indentation
}
}
Usage in an Angular template:
<pre>{{ someJsonObject | jsonPrettyPrint }}</pre>
<!-- Outputs the JSON object in a nicely formatted way for debugging -->
20. Password Strength Pipe
Checks the strength of a password and provides feedback on its complexity, such as “Weak,” “Medium,” or “Strong.” The implementation can vary depending on the criteria used to determine password strength.
Here’s a simplified example that evaluates based on length and complexity:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'passwordStrength' })
export class PasswordStrengthPipe implements PipeTransform {
transform(password: string): string {
if (!password) return '';
if (password.length < 6) {
return 'Weak';
} else if (password.length < 10) {
return 'Medium';
} else {
// You can add more criteria for a "Strong" password
return 'Strong';
}
}
}
Usage in an Angular template:
<p>{{ 'Pass123' | passwordStrength }}</p>
<!-- Output: "Medium" -->
<p>{{ 'StrongPassword123' | passwordStrength }}</p>
<!-- Output: "Strong" -->
21. Ordinal Number Pipe
Converts a number into its corresponding ordinal representation (e.g., 1st, 2nd, 3rd, 4th, etc.).
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'ordinalNumber' })
export class OrdinalNumberPipe implements PipeTransform {
transform(number: number): string {
if (isNaN(number)) return '';
const lastDigit = number % 10;
if (lastDigit === 1 && number !== 11) {
return number + 'st';
} else if (lastDigit === 2 && number !== 12) {
return number + 'nd';
} else if (lastDigit === 3 && number !== 13) {
return number + 'rd';
} else {
return number + 'th';
}
}
}
Usage in an Angular template:
<p>{{ 1 | ordinalNumber }}</p>
<!-- Output: "1st" -->
<p>{{ 22 | ordinalNumber }}</p>
<!-- Output: "22nd" -->
<p>{{ 13 | ordinalNumber }}</p>
<!-- Output: "13th" -->
<p>{{ 7 | ordinalNumber }}</p>
<!-- Output: "7th" -->
22. URLify Pipe
Converts a string into a URL-friendly format, replacing spaces with hyphens and removing special characters.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'urlify' })
export class URLifyPipe implements PipeTransform {
transform(input: string): string {
if (!input) return '';
return input
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^\w-]+/g, ''); // Remove non-word characters except hyphens
}
}
Usage in an Angular template:
<p>{{ 'This is a URL-friendly title!' | urlify }}</p>
<!-- Output: "this-is-a-url-friendly-title" -->
23. Relative Time Pipe
Displays timestamps in a relative format, like “just now,” “a few minutes ago,” or “yesterday.” You can use a library like date-fns for this purpose.
First, install the date-fns library:
npm install date-fns
Then, create the RelativeTimePipe:
import { Pipe, PipeTransform } from '@angular/core';
import { formatDistanceToNow } from 'date-fns';
@Pipe({ name: 'relativeTime' })
export class RelativeTimePipe implements PipeTransform {
transform(timestamp: number | Date): string {
if (!timestamp) return '';
return formatDistanceToNow(timestamp, { addSuffix: true });
}
}
Usage in an Angular template:
<p>{{ someTimestamp | relativeTime }}</p>
<!-- Example: "just now," "a few minutes ago," "yesterday," etc. -->
24. Array Shuffle Pipe
Shuffles the elements of an array, creating a random order for display.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'arrayShuffle' })
export class ArrayShufflePipe implements PipeTransform {
transform(array: any[]): any[] {
if (!array) return array.slice();
let currentIndex = array.length, randomIndex, temporaryValue;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
}
Usage in an Angular template:
<ul>
<li *ngFor="let item of items | arrayShuffle">{{ item }}</li>
</ul>
25. Color Contrast Pipe
Determines the best text color (black or white) to ensure good contrast against a background color. The pipe below assumes that the background color is provided in hexadecimal format.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'colorContrast' })
export class ColorContrastPipe implements PipeTransform {
transform(backgroundColor: string): string {
if (!backgroundColor) return '';
// Calculate the brightness of the background color
const r = parseInt(backgroundColor.slice(1, 3), 16);
const g = parseInt(backgroundColor.slice(3, 5), 16);
const b = parseInt(backgroundColor.slice(5, 7), 16);
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
// Determine the text color for good contrast
return brightness > 128 ? 'black' : 'white';
}
}
Usage in an Angular template:
<div [style.background-color]="'#3498db'" [style.color]="'#3498db' | colorContrast">
Text with contrast
</div>
26. Roman Numeral Pipe
Converts Arabic numerals to Roman numerals and vice versa. This implementation handles the conversion from Arabic to Roman numerals.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'romanNumeral' })
export class RomanNumeralPipe implements PipeTransform {
transform(arabicNumber: number): string {
if (isNaN(arabicNumber) || arabicNumber < 1 || arabicNumber > 3999) return '';
const romanNumerals = [
'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'
];
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let roman = '';
for (let i = 0; i < romanNumerals.length; i++) {
while (arabicNumber >= values[i]) {
roman += romanNumerals[i];
arabicNumber -= values[i];
}
}
return roman;
}
}
Usage in an Angular template:
<p>{{ 1984 | romanNumeral }}</p>
<!-- Output: "MCMLXXXIV" -->
27. Sentence Case Pipe
Capitalize the first letter of each sentence in a block of text.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sentenceCase' })
export class SentenceCasePipe implements PipeTransform {
transform(text: string): string {
if (!text) return '';
return text.replace(/(^\s*|\.\s*)([a-z])/g, (_, separator, letter) => separator + letter.toUpperCase());
}
}
Usage in an Angular template:
<p>{{ 'this is a sentence. this is another. the third.' | sentenceCase }}</p>
<!-- Output: "This is a sentence. This is another. The third." -->
28. CSV To Array Pipe
Parses a CSV (Comma-Separated Values) string into an array for easier data manipulation. The example below assumes that the CSV data is provided as a string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'csvToArray' })
export class CSVToArrayPipe implements PipeTransform {
transform(csvData: string): string[] {
if (!csvData) return [];
// Split the CSV string into an array
return csvData.split(',');
}
}
Usage in an Angular template:
<ul>
<li *ngFor="let item of 'apple,banana,cherry' | csvToArray">{{ item }}</li>
</ul>
29. Slugify Pipe
Converts a string into a URL slug by removing special characters, converting spaces to hyphens, and making it lowercase.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'slugify' })
export class SlugifyPipe implements PipeTransform {
transform(input: string): string {
if (!input) return '';
return input
.toLowerCase()
.replace(/[^a-z0-9 -]/g, '') // Remove special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-'); // Remove consecutive hyphens
}
}
Usage in an Angular template:
<p>{{ 'This is a Slug Example!' | slugify }}</p>
<!-- Output: "this-is-a-slug-example" -->
30. Random Placeholder Image Pipe
Generates random placeholder images with varying colors and patterns, suitable for mockups and testing. For this pipe, we’ll generate a random URL for a placeholder image.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'randomPlaceholderImage' })
export class RandomPlaceholderImagePipe implements PipeTransform {
transform(width: number = 200, height: number = 150): string {
const colors = ['333333', '666666', '999999', 'CCCCCC'];
const patterns = ['abstract', 'animals', 'business', 'food', 'nature', 'people', 'sports', 'technics', 'transport'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
const randomPattern = patterns[Math.floor(Math.random() * patterns.length)];
return `https://via.placeholder.com/${width}x${height}/${randomColor}/${randomPattern}`;
}
}
Usage in an Angular template:
<img [src]="'200x150' | randomPlaceholderImagimport { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneNumberMask' })
export class PhoneNumberMaskPipe implements PipeTransform {
transform(phoneNumber: string): string {
if (!phoneNumber) return '';
// Add your custom logic for phone number masking and formatting
// Example: (123) ***-****
}
}e" alt="Random Placeholder Image">
<!-- Generates a random placeholder image URL with a size of 200x150 pixels -->
31. Phone Number Mask Pipe
Formats a phone number by adding separators and masking characters for privacy.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneNumberMask' })
export class PhoneNumberMaskPipe implements PipeTransform {
transform(phoneNumber: string): string {
if (!phoneNumber) return '';
// Add your custom logic for phone number masking and formatting
// Example: (123) ***-****
}
}
Usage in an Angular template:
<p>{{ '1234567890' | phoneNumberMask }}</p>
<!-- Output: "(123) ***-****" -->
Conclusion
Custom pipes are a powerful tool in Angular, allowing you to tailor data formatting and transformation to your specific needs. The 31 examples provided here offer a glimpse into the versatility and utility of custom pipes, and you can adapt and expand upon them to meet your project’s unique requirements.
In your Angular development journey, mastering custom pipes will undoubtedly be a valuable to create more dynamic and user-friendly applications.
Happy coding!
Learn more
[embed]What are Pipes in Angular? What are Pipes in Angular?blog.bitsrc.io
메타데이터
- post_id
- c7ce8ec7faae
- slug
- mastering-custom-pipes-in-angular-31-real-world-examples-2023-c7ce8ec7faae
- url
- https://medium.com/bitsrc/mastering-custom-pipes-in-angular-31-real-world-examples-2023-c7ce8ec7faae
- canonical_url
- https://medium.com/bitsrc/mastering-custom-pipes-in-angular-31-real-world-examples-2023-c7ce8ec7faae
- author_url
- https://medium.com/@astritshuli
- status
- ok
- fetched_at
- 2026-07-24 22:02:14