Instructions:
Research the Definition of Angular Pipes:
Understand what Angular Pipes are and their purpose.
- Angular Pipes is a special operator that can able direct a data within html. It’s like a tunnel wherein it transforms from place into another. The mainly purpose of angular pipes to make more simplified the structure of code. Angular pipes it’s like a converting from its data then process when it transformed the result. There’s a lot of various data pipes can we use.
Learn how pipes are used to transform data in templates (e.g., formatting dates, numbers, strings).
Formatting dates
<p>The date is {{ today | date:'fullDate' }}</p>
In that code snippets display interpolation inside of double curly bracket or called data binding. In this case, discuss the pipes, so for example, today variable hold a value of today’s date for example. then, the operator “I” use to apply the pipe into the date. it accesses through pipes of date, the format of fulldate will display which is the Friday, September 27, 2024.
If shortdate format use
<p>The date is {{ today | shortDate }}</p>
Result: The date is 09/27/2024
<p>The date is {{ today | longDate }}</p>
Result: (Same to the fulldate) Friday, September 27, 2024
Formatting numbers
<p>The number is {{ 3.14159 | number:'1.2-3' }}</p>
In this code snippets, it shows a Pi number which is 3.14159, pipe was number. In 1.2-3, the 1 only specify the minimum number can use before it decimal point. The 2-3 is the minimum and maximum number after decimal point.
Formatting Strings
<p>{{ 'GEEKSFORGEEKS' | lowercase }}</p>
In this code snippets, shows the string ‘GEEKSFORGEEKS’. Using operator the pipe lowercase will be use to make a lowercase the GEEKSFORGEEKS. so possible the transform of that is like this
<p>geeksforgeeks</p>
This is the actual in html, but in browser, only the text will display.
Vise versa when you make the sentence or word capital letter, use pipe uppercase.
Types of Angular Pipes:
- Research built-in pipes such as DatePipe, CurrencyPipe, DecimalPipe, UpperCasePipe, LowerCasePipe, SlicePipe, and more.
DatePipe
<p>{{ currentDate | date: 'fullDate' }}</p>
This syntax use a currentDate variable with a value of current date today in components, then operator I to connect in date pipes with a format fullDate. So the outcome will “Saturday, September 28, 2024”.
CurrencyPipe
<p>{{ 12345.6789 | currency: 'INR' }}</p>
This syntax shows the value of currency. THE INR is the abbreviated currency. In this example that is a Indian Rupees. So, the output will become that already round off.
12,345,68
DecimalPipe
<p>{{ 12345.6789 | number: '1.2-2' }}</p>
So, the 12345.6789 is the direct value and want to pipe number, so once again the format inside of pipenumber 1.2.2, 1 is the maximum number before decimal point, then 2-2. is 2 minimum and maximum number after decimal point. so the out
- UpperCasePipe
<p>{{ 'hello world' | uppercase }}</p>
In this syntax shows the direct value string ‘hello world” with a pipe use uppercase so the outcome will be HELLO WORLD. same in
LowerCasePipe
<p>{{ 'hello world' | lowercase }}</p>
SlicePipe
{{ value | SlicePipe }}
SlicePipe is used to create an array containing a slice of the element. So if the value variable contains of value named “GeeksforGeeks”, the outcome using SlicePipe will be
Geeks
For
Geeks
- Explore how to create custom pipes when built-in pipes don't meet the requirements.
How make customized pipes just for when the built-in pipes not passed the requirements, this is alternative way to do.
Pipe implements the PipeTransform interface. As the name suggests, it receives the value and transforms it into the desired format with the help of a transform() method.
Here are the general steps to create a custom pipe:
Create a TypeScript Class with an export keyword.
Decorate it with the @Pipe decorator and pass the name property to it.
Implement the pipe transform interface in the class.
Implement the transform method imposed due to the interface.
Return the transformed data with the pipe.
Add this pipe class to the declarations array of the module where you want to use it.
Alternatively, you can use the following command,
Once run, two files are created.
The pipe.ts file holds the following code.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'demopipe'
})
export class DemopipePipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return null;
}
}
As you can see, the PipeTransform interface and the transform method have been created. We’ve highlighted it for better understanding.
For the example purpose, we have created a pipe that reverses a given string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
nvalue: string
transform(value: any, ...args): any {
this.nvalue = value.split('').reverse().join('');
return this.nvalue;
}
}
Now in our app.component.html “ I” display a string and it is reverse using the pipe name
<h3>
The reverse of string is {{ "string" | reverse}}
</h3>
You can also join multiple pipes
<h3>
The reverse of string is {{ "string" | reverse | uppercase}}
</h3>
The output looks like this.
Use Cases of Angular Pipes:
Identify practical use cases for using pipes in Angular applications (e.g., displaying formatted dates, converting text to uppercase).
Angular pipes are powerful tools that can transform data displayed in templates, enhancing the user experience and readability. Here are some practical use cases for using pipes in Angular applications:
Date Formatting:
Use the
DatePipe
to display dates in various formats (e.g., long, medium, short) based on user preferences or locales.Example: Displaying a timestamp as "September 28, 2024" instead of "2024-09-28".
Currency Formatting:
Use the
CurrencyPipe
to format numbers as currency, automatically including the appropriate currency symbol and formatting based on the user's locale.Example: Displaying prices in a shopping cart as "$29.99" instead of "29.99".
Uppercase and Lowercase Conversion:
Use
UpperCasePipe
andLowerCasePipe
to convert text to uppercase or lowercase.Example: Displaying user names consistently in uppercase as "JOHN DOE".
Percentage Formatting:
Use the
DecimalPipe
or a custom pipe to display numbers as percentages, which is useful in financial or statistical applications.Example: Showing a discount as "25%" instead of "0.25".
Custom Text Transformations:
Create custom pipes for specific text transformations, such as reversing a string, truncating long text, or converting text to title case.
Example: Truncating a long article preview to 100 characters.
Filtering and Sorting Data:
Use custom pipes to filter or sort lists of items directly in the template, making it easier for users to find specific items.
Example: Filtering a list of products based on user input.
JSON Formatting:
Use the
JsonPipe
to display objects in a readable JSON format, which can be helpful for debugging.Example: Showing API response data in a user-friendly way.
Safe HTML Rendering:
Use a custom pipe to sanitize and render HTML content safely in templates, preventing XSS attacks.
Example: Displaying user-generated content or blog posts with HTML formatting.
Time Calculations:
Use custom pipes to calculate and display relative time (e.g., "2 hours ago", "in 3 days") from timestamps.
Example: Showing how long ago a post was made.
Custom Formatting:
Create custom pipes to format specific types of data, such as phone numbers, social security numbers, or addresses.
Example: Formatting a phone number as "(123) 456-7890".
Find examples where pipes are used for dynamic data transformation in a user-friendly format.
- The example also provided on the first question still I put down once again what angular pipes are used for dynamic data transformation.
Dynamic Date Formating: DatePipe
<p>Last login: {{ lastLoginDate | date:'fullDate' }}</p>
lastLoginDate will be a variable that holds a value from the typescript, date is a pipe use as a tunnel and format to make it reusability code.
Dynamic Currency Formatting: CurrencyPipe
<p>Price: {{ price | currency:currencyCode:true }}</p>
In this case, This code displays a price, formatted as currency. The inside 2 curly backet binds a price variable and formats it according to the currencycode. The true adds the currency symbol like in peso ₱, in america , $, and so on.
Uppercase and Lowercase Transformation: UppercasePipe, LowercasePipe
<p>Username: {{ username | uppercase }}</p>
this a direct value that need only to uppercase using its pipe. What ever value of username it will show uppercase and vise versa if we want lowercase.
Dynamic Percentage Display: PercentPipe
<p>Profit: {{ profit | percent:'2.0-2' }}</p>
In this, syntax, profit that holds a value from a typescript using operator I or that just in case, the pipePercent, with a 2 minimum digits before decimal point and 0-2 after decimal point will be the minimum at maximum number.
Dynamic Decimal Transformation: DecimalPipe
<p>Average Score: {{ averageScore | number:'1.1-2' }}</p>
Same in this case, with variable averageScore hold a value from typescript. with a 2 minimum digits before decimal point and 0-2 after decimal point will be the minimum at maximum number.
Text Truncation for Previews:
<p>{{ articleContent | truncate:100 }}</p>
This code snippet displays a portion of the articleContent variable, truncated to a maximum of 100 characters. If the content exceeds 100 characters, it will be cut off, typically followed by an ellipsis (e.g., "..."), indicating that there is more content available.
The output will be::
"This is an example of a long article content that will be truncated if it exceeds the specified..."
Dynamic Filtering of Lists: FilterPipe
<li *ngFor="let product of products | filter:searchTerm">
{{ product.name }}
</li>
This code snippet is an Angular template using the *ngFor directive to iterate over a list of products.
*ngFor="let product of products | filter:searchTerm": This part loops through each item in the products array, applying a filter pipe that filters the products based on the searchTerm. In addition,
{{ product.name }}: Inside the loop, it displays the name property of each product.
The output will be a list item (<li>) for each product that matches the search term, showing the product's name. If no products match the search term, the list will be empty.
Real-time Relative Time Display: RelativePipe
<p>Posted {{ postDate | relativeTime }}</p>
{{ postDate | relativeTime }} takes the postDate varibale and changes it into a simple time format, like "3 days ago" or "just now."
Add References:
- Cite all the resources and websites where you found information and examples (official Angular documentation, blogs, tutorials).
LINKS:
Pipes | Learn Angular (learn-angular.com)
Formatting Numbers and Dates in Angular Using Pipes (angulardive.com)
Pipes in Angular - GeeksforGeeks
https://www.simplilearn.com/tutorials/angular-tutorial/angular-pipes