当前位置: 首页>后端>正文

Angular自定义管道

Angular 提供了一个强大的“管道”(pipes) 功能来转换和格式化模板中的数据。虽然 Angular 包含各种内置管道,但有时您可能需要创建自定义管道以满足您的应用程序要求。

在本文中,我们将探讨 Angular 中自定义管道的概念,并通过 31 个真实示例来演示其实际用法。

What are Angular Pipes什么是管道?

Angular 管道是简单的函数,允许您直接在模板中转换和格式化数据。它们通过在 HTML 模板中添加管道运算符 ( | ) 来使用。Angular 为常见任务提供了几个内置管道,例如格式化日期、货币和文本转换。自定义管道通过允许您创建数据转换逻辑来扩展此功能。

Creating a Custom Pipe 创建自定义管道

在深入研究示例之前,让我们了解如何在 Angular 中创建自定义管道。可以通过实现 PipeTransform 接口并在 transform 方法中提供转换逻辑来创建自定义管道。

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

@Pipe({
name: 'customPipeName'
})
export class CustomPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
// Your transformation logic here
}
}

自定义管道示例

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).
电话号码格式化程序管道:将原始数字字符串格式化为结构良好的电话号码格式(例如,(555) 555–5555)。
File Size Pipe: Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
文件大小管道:将文件大小(以字节为单位)转换为更易于阅读的格式,例如 KB、MB 或 GB。
Markdown To HTML Pipe: Transforms Markdown text into HTML for rendering within your application.
Markdown 转 HTML 管道:将 Markdown 文本转换为 HTML,以便在应用程序中呈现。
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”).
Time Ago Pipe:显示时间戳的人类友好表示形式,指示事件发生的时间(例如,“3 小时前”或“昨天”)。
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.
Initials Pipe:从全名中提取并显示首字母缩写,这对于用户配置文件显示很有用。
Strip HTML Tags Pipe: Removes all HTML tags from a given string, ensuring that only plain text is displayed.
剥离 HTML 标记管道:从给定字符串中删除所有 HTML 标记,确保仅显示纯文本。
Camel Case To Spaces Pipe: Converts camelCase or PascalCase strings into human-readable sentences with spaces.
Camel Case To Spaces Pipe:将 camelCase 或 PascalCase 字符串转换为带有空格的人类可读句子。
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.
Pluralize Pipe:根据提供的计数处理单词的复数。例如,当计数大于 1 时,它可以将“item”更改为“items”。
Humanize Duration Pipe: Converts a duration in seconds into a more human-readable format, like “2 hours and 30 minutes.”
人性化持续时间管道:将持续时间(以秒为单位)转换为更易于阅读的格式,例如“2 小时 30 分钟”。
JSON Pretty Print Pipe: Takes a JSON object and pretty-prints it, making it more readable for debugging purposes.
JSON Pretty Print Pipe:获取 JSON 对象并对其进行漂亮打印,使其在调试时更具可读性。
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.).
序数管道:将数字转换为其相应的序数表示形式(例如,第 1、2、3、4 等)。
URLify Pipe: Converts a string into a URL-friendly format, replacing spaces with hyphens and removing special characters.
URLify Pipe:将字符串转换为对 URL 友好的格式,将空格替换为连字符并删除特殊字符。
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.
CSV 到数组管道:将 CSV(逗号分隔值)字符串解析为数组,以便于数据操作。
Slugify Pipe: Converts a string into a URL slug by removing special characters, converting spaces to hyphens, and making it lowercase.
Slugify Pipe:通过删除特殊字符、将空格转换为连字符并使其小写,将字符串转换为 URL slug。
Random Placeholder Image Pipe: Generates random placeholder images with varying colors and patterns, suitable for mockups and testing.
随机占位符图像管道:生成具有不同颜色和图案的随机占位符图像,适用于模型和测试。
Password Strength Pipe: Evaluates the strength of a password and provides feedback, such as weak, medium, or strong, based on predefined criteria.
密码强度管道:评估密码的强度,并根据预定义的条件提供反馈,例如弱、中或强。

Uppercase First Pipe 1. 大写第一根管

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:
在 Angular 模板中的用法:
<p>{{ 'hello world' | uppercaseFirst }}</p>

Reverse String Pipe 2. 反向串管

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:
在 Angular 模板中的用法:
<p>{{ 'Angular' | reverseString }}</p>

Filter Array Pipe 3. 滤波器阵列管

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:
在 Angular 模板中的用法:
<ul>
<li *ngFor="let item of items | filterArray:'category':'Electronics'">{{ item.name }}</li>
</ul>

Truncate Text Pipe 4.截断文本管道

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:
在 Angular 模板中的用法:
<p>{{ 'This is a long text that should be truncated' | truncateText:20 }}</p>

Sort Array Pipe 5. 排序数组管道

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:
在 Angular 模板中的用法:
<ul>
<li *ngFor="let item of items | sortArray:'price':'asc'">{{ item.name }} - {{ item.price }}</li>
</ul>

  1. 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:
在 Angular 模板中的用法:
<p>{{ 100 | currencyConverter:1.2 }}</p>

  1. Phone Number Formatter Pipe

电话号码格式化Formatter程序管道

Formats a raw string of numbers into a well-structured phone number format (e.g., (555) 555–5555).
将原始数字字符串格式化为结构良好的电话号码格式(例如,(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:
在 Angular 模板中的用法:
<p>{{ '1234567890' | phoneNumberFormatter }}</p>

File Size Pipe 8.文件大小管道

Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
将文件大小(以字节为单位)转换为更易于阅读的格式,如 KB、MB 或 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:
在 Angular 模板中的用法:
<p>{{ 1024 | fileSize }}</p>

Markdown To HTML Pipe 9. Markdown 转 HTML 管道

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.
将 Markdown 文本转换为 HTML,以便在 Angular 应用程序中呈现。要使用此管道,您可以使用一个库,例如 marked 将 Markdown 转换为 HTML。
First, you need to install the marked library:
首先,您需要安装 marked 库:
npm install marked
Then, create the MarkdownToHTMLPipe:
然后,创建 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:
在 Angular 模板中的用法:
<div [innerHtml]="markdownText | markdownToHtml"></div>

Time Ago Pipe 10. Time Ago 管道

Displays a human-friendly representation of a timestamp, indicating how long ago an event occurred (e.g., “3 hours ago” or “yesterday”).
显示时间戳的人类友好表示形式,指示事件发生的时间(例如,“3 小时前”或“昨天”)。
To implement a TimeAgo pipe, you can use a library like date-fns to calculate the relative time.
要实现 TimeAgo 管道,可以使用库 like date-fns 来计算相对时间。
First, install the date-fns library:
首先,安装 date-fns 库:
npm install date-fns
Create the TimeAgoPipe: 创建 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:
在 Angular 模板中的用法:
<p>{{ someTimestamp | timeAgo }}</p>

  1. Percent Change Pipe 11. 百分比变化管
    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:
在 Angular 模板中的用法:
<p>{{ 85 | percentChange:100 }}</p>

Initials Pipe 12. 首字母管道

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:
在 Angular 模板中的用法:
<p>{{ 'John Doe' | initials }}</p>

Strip HTML Tags Pipe 13. 剥离 HTML 标签管道

Removes all HTML tags from a given string, ensuring that only plain text is displayed.
从给定字符串中删除所有 HTML 标记,确保仅显示纯文本。
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:
在 Angular 模板中的用法:
<p>{{ '<p>This is <b>HTML</b> text</p>' | stripHtmlTags }}</p>

Camel Case To Spaces Pipe 14. 驼峰命名到空格管道

Converts camelCase or PascalCase strings into human-readable sentences with spaces.
将 camelCase 或 PascalCase 字符串转换为带空格的人类可读句子。
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, 'Angular自定义管道,1,第1张2');
}
}
Usage in an Angular template:
在 Angular 模板中的用法:
<p>{{ 'camelCaseExample' | camelCaseToSpaces }}</p>

Title Case Pipe 15. 标题案例管道

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:
在 Angular 模板中的用法:
<p>{{ 'this is a title case example' | titleCase }}</p>

Masked Input Pipe 16. Masked输入管道

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:
在 Angular 模板中的用法:
<input [ngModel]="'1234567890'" [ngModelOptions]="{updateOn: 'blur'}" [value]="'(***) ***-****' | maskedInput">

Pluralize Pipe 17. 复数管道

Handles pluralization of words based on the count provided. It can change “item” to “items” when the count is greater than one.
根据提供的计数处理单词的复数。当计数大于 1 时,它可以将“item”更改为“items”。
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:
在 Angular 模板中的用法:
<p>{{ 1 | pluralize:'item' }}</p>

<p>{{ 5 | pluralize:'item' }}</p>

  1. Humanize Duration Pipe
    18.人性化持续时间管道
    Converts a duration in seconds into a more human-readable format, like “2 hours and 30 minutes.”
    将持续时间(以秒为单位)转换为更易于阅读的格式,例如“2 小时 30 分钟”。
    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:
在 Angular 模板中的用法:
<p>{{ 7200 | humanizeDuration }}</p>

<p>{{ 150 | humanizeDuration }}</p>

<p>{{ 30 | humanizeDuration }}</p>

<p>{{ 0 | humanizeDuration }}</p>

  1. JSON Pretty Print Pipe
  2. JSON 漂亮的打印管道
    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.
    获取 JSON 对象并对其进行漂亮的打印,使其更具可读性,以便进行调试。为此,可以使用带有 spacing 参数的方法 JSON.stringify 。
    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:
在 Angular 模板中的用法:
<pre>{{ someJsonObject | jsonPrettyPrint }}</pre>

  1. Password Strength Pipe
  2. 密码强度管
    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:
在 Angular 模板中的用法:
<p>{{ 'Pass123' | passwordStrength }}</p>

<p>{{ 'StrongPassword123' | passwordStrength }}</p>

  1. Ordinal Number Pipe 21. 序数管道
    Converts a number into its corresponding ordinal representation (e.g., 1st, 2nd, 3rd, 4th, etc.).
    将数字转换为其相应的序数表示形式(例如,第 1、2、3、4 等)。
    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:
在 Angular 模板中的用法:
<p>{{ 1 | ordinalNumber }}</p>

<p>{{ 22 | ordinalNumber }}</p>

<p>{{ 13 | ordinalNumber }}</p>

<p>{{ 7 | ordinalNumber }}</p>

  1. URLify Pipe 22. URLify 管道
    Converts a string into a URL-friendly format, replacing spaces with hyphens and removing special characters.
    将字符串转换为 URL 友好的格式,将空格替换为连字符并删除特殊字符。
    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:
在 Angular 模板中的用法:
<p>{{ 'This is a URL-friendly title!' | urlify }}</p>

  1. Relative Time Pipe 23. 相对时间管道
    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.
    以相对格式显示时间戳,例如“刚刚”、“几分钟前”或“昨天”。为此,您可以使用类似的 date-fns 库。
    First, install the date-fns library:
    首先,安装 date-fns 库:
    npm install date-fns
    Then, create the RelativeTimePipe:
    然后,创建 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:
在 Angular 模板中的用法:
<p>{{ someTimestamp | relativeTime }}</p>

  1. Array Shuffle Pipe 24. 数组随机管
    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:
在 Angular 模板中的用法:
<ul>
<li *ngFor="let item of items | arrayShuffle">{{ item }}</li>
</ul>

  1. Color Contrast Pipe 25. 颜色对比管
    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:
在 Angular 模板中的用法:
<div [style.background-color]="'#3498db'" [style.color]="'#3498db' | colorContrast">
Text with contrast
</div>

  1. Roman Numeral Pipe 26. 罗马数字管
    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:
在 Angular 模板中的用法:
<p>{{ 1984 | romanNumeral }}</p>

  1. Sentence Case Pipe 27. 句子大小写管道
    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:
在 Angular 模板中的用法:
<p>{{ 'this is a sentence. this is another. the third.' | sentenceCase }}</p>

  1. CSV To Array Pipe
  2. .CSV到数组管道
    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.
    将 CSV(逗号分隔值)字符串解析为数组,以便于数据操作。下面的示例假定 CSV 数据以字符串形式提供。
    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:
在 Angular 模板中的用法:
<ul>
<li *ngFor="let item of 'apple,banana,cherry' | csvToArray">{{ item }}</li>
</ul>

  1. Slugify Pipe 29. 蛞蝓管
    Converts a string into a URL slug by removing special characters, converting spaces to hyphens, and making it lowercase.
    通过删除特殊字符、将空格转换为连字符并使其小写,将字符串转换为 URL slug。
    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:
在 Angular 模板中的用法:
<p>{{ 'This is a Slug Example!' | slugify }}</p>

  1. Random Placeholder Image Pipe
  2. 随机占位符图像管道
    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.
    生成具有不同颜色和图案的随机占位符图像,适用于模型和测试。对于此管道,我们将为占位符图像生成一个随机 URL。
    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:
在 Angular 模板中的用法:
<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">

  1. Phone Number Mask Pipe
  2. 电话号码掩膜管
    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:
在 Angular 模板中的用法:
<p>{{ '1234567890' | phoneNumberMask }}</p>

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.
自定义管道是 Angular 中一个强大的工具,允许您根据特定需求定制数据格式和转换。这里提供的 31 个示例让我们一窥定制管道的多功能性和实用性,您可以对其进行调整和扩展,以满足您项目的独特要求。
In your Angular development journey, mastering custom pipes will undoubtedly be a valuable to create more dynamic and user-friendly applications.
在您的 Angular 开发之旅中,掌握自定义管道无疑对于创建更动态和用户友好的应用程序很有价值。


https://www.xamrdz.com/backend/3rd1941516.html

相关文章: