Pipes in Angular are simple functions used to transform data in templates without modifying the underlying data. Pipes take in a value, process it, and return a formatted or transformed output. They are often used for formatting dates, numbers, strings, and even arrays or objects.
They allow you to format and display data in a more readable or relevant format directly in the view without altering the underlying data model.
Using pipes helps in keeping the code clean and readable. Instead of writing complex logic in the templates or components, you can encapsulate that logic in a pipe, which can then be reused across different parts of your application.
For example, if you’re developing a blog platform where users can see the publication date of articles. Dates need to be displayed in a user-friendly format, such as “August 31, 2024,” instead of the raw format “2024–08–31T14:48:00.000Z”. With pipes, you can use Angular’s built-in DatePipe in the template instead of manually formatting the date in the component, cluttering the code and reducing readability.
<p>Published on: {{ article.publishDate | date:'longDate' }}</p>
To apply a pipe, use the pipe operator (|) within a template expression as shown in the above code example.
Built-in Pipes
Angular comes with several built-in pipes that cover common tasks (DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, AsyncPipe, JsonPipe, etc.). Knowing how to use these can make your code cleaner and more efficient.
Examples:
<pre class="brush:php;toolbar:false">{{ user | json }}
Price: {{ product.price | currency:'USD' }}
{{ user.name | uppercase }}
Parametrized Pipes
Many Angular pipes accept parameters to customize their behavior.
To specify the parameter, follow the pipe name with a colon (:) and the parameter value
Some pipes accept multiple parameters, which are separated by additional colons.
Parameters can be optional or required. Suppose you have a custom pipe that formats currency and requires you to specify the currency type as a parameter. If this parameter is not provided, the pipe might not be able to format the value correctly.
<p>The product price is {{ price | customCurrency:'USD' }}</p>
1. DatePipe with Parameters
<p>Published on: {{ article.publishDate | date:'MMMM d, y, h:mm:ss a' }}</p>
This formats the date as “August 31, 2024, 2:48:00 PM”.
2. CurrencyPipe with Parameters
<p>Price: {{ product.price | currency:'EUR':'symbol-narrow':'1.0-0' }}</p>
This formats the price as “€1,235” (rounded to no decimal places).
Chaining Pipes
You can chain multiple pipes together to achieve complex transformations.
<p>{{ article.content | slice:0:100 | uppercase }}</p>
This will slice the first 100 characters of article.content and convert them to uppercase.
Custom Pipes
Sometimes, the built-in pipes may not meet your specific needs and you will need to create a custom pipe to handle the specific logic. Here’s how you can do it.
Example:
In the following example we are going to create a pipe that adds a greeting to a name like “Hello, Alice!”
Run the following command to generate a new pipe:
ng generate pipe greet
Now, let’s modify the greet.pipe.ts file in the src/app directory to include the pipe logic:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'greet', // This is the name you'll use in the template standalone: true, }) export class GreetPipe implements PipeTransform { transform(value: string): string { return `Hello, ${value}!`; // This is the transformation logic } }
Once your pipe is ready, you can use it in your templates.
<p>{{ 'Alice' | greet }}</p>
Creating a Parameterized Custom Pipe
Now we are going to make the greeting customizable, so you can say “Hi, Alice!” or “Welcome, Alice!” depending on what you pass to the pipe.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'greet', // Same pipe name as before standalone: true, }) export class GreetPipe implements PipeTransform { transform(value: string, greeting: string = 'Hello'): string { return `${greeting}, ${value}!`; // Now it uses the greeting passed in } }
The transform method now has a second parameter, greeting. If no greeting is provided, it defaults to “Hello”.
Now you can customize the greeting in your templates.
<p>{{ 'Alice' | greet:'Hi' }}</p> <p>{{ 'Bob' | greet:'Welcome' }}</p>
Pure vs. Impure Pipes
1. Pure Pipes
By default, all Angular pipes are pure. A pure pipe only gets called when input data (like a number or a string) or when the reference to an object (like an array or date) changes. This makes pure pipes efficient and performant because the pipe doesn’t run unnecessarily.
However, if your data is more complex, like an array of items, Angular might not notice changes inside the array (like adding a new item) because the reference to the array hasn’t changed.
Unless necessary, keep your pipes pure to avoid unnecessary re-renders and to maintain performance.
Example:
@Pipe({ name: "onSale", standalone: true, pure: true, }) export class OnSalePipe implements PipeTransform { transform(items: Item[]): Item[] { return items.filter((item) => item.isOnSale); } }
In your template:
- {{ item.name }} - {{ item.price | formatPrice }}
If you add a new item to the items array that’s on sale, you might expect it to show up in the list. But if you simply push the new item into the array, the list might not update because the array reference hasn’t changed.
2. Impure Pipes
An impure pipe, on the other hand, is called every time Angular performs a change detection cycle. However, because they run so often, they can slow down your app.
Example:
@Pipe({ name: "onSaleImpure", standalone: true, pure: false, }) export class OnSaleImpurePipe implements PipeTransform { transform(items: Item[]): Item[] { return items.filter((item) => item.isOnSale); } }
In your template:
- {{ item.name }} - {{ item.price | formatPrice }}
Now, when you add a new item, the pipe will notice the change and update the list.
Best Practices for Using Pipes
Keep Pipes Simple. Avoid Heavy Computations in Pipes
Name Pipes Clearly and Descriptively
Keep Pipes Focused on a Single Responsibility
Avoid Impure Pipes When Possible
Test Custom Pipes Thoroughly
Conclusion
Angular pipes streamline data transformation tasks, making your code more modular, reusable, and maintainable. They help to enforce consistency across the application and improve the readability of your templates, which is crucial for developing scalable and maintainable applications.
The above is the detailed content of Angular Pipes: A Comprehensive guide. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment