Angular Pipes
Angular's pipes feature lets you modify data in your application before showing it to the user. Pipes can be used with template-driven and reactive forms, as well as with other Angular components and services. They are used to format, filter, and sort data.
Pipes in Angular can be pure or impure.
Since pure pipes are meant to be stateless, their output cannot be impacted by any internal states.
Rather, they receive input data and produce output data that has been altered. Additionally, pure pipes are memoized, meaning that they won't be run again if the input data hasn't changed since the pipe was last called.
Since pure pipes only run when necessary, they have the advantage of helping your Angular application perform better. Furthermore, pure pipes can lessen the need for pointless change detection cycles, which can enhance the performance of an application as a whole.
To create a pure pipe in Angular, you need to add the pure: true option to the @Pipe decorator, like this:
@Pipe({
name: 'myPurePipe',
pure: true
})
Impure pipes can be useful in some cases, such as when you need to perform a heavy calculation or retrieve data from an external API.
However, it’s generally recommended to use pure pipes whenever possible to improve performance and prevent unnecessary change detection cycles.
Built-in Pipes in Angular
Angular comes with a set of built-in pipes that you can use in your templates. Here are some of the most commonly used built-in pipes in Angular:
Currency Pipe
Date Pipe
Json Pipe
LowerCase Pipe
UpperCase Pipe
PercentPipe
SlicePipe
TitleCasePipe
AsyncPipe
1. Currency Pipe
CurrencyPipeis a built-in pipe in Angular that is used to format a number as a currency value.
It provides a way to display currency values in a user-friendly format, taking into account the currency symbol, decimal separator, and grouping separators based on the current locale.
Here’s an example of how to use the CurrencyPipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
price: number = 12345.6789;
}
app.component.html:
<div>
<h2>Using CurrencyPipe</h2>
<p>Price: {{ price | currency }}</p>
<p>Price: {{ price | currency:'EUR':'symbol-narrow':'4.2-2' }}</p>
</div>
In the above example, we have a price variable that holds a number value of 12345.6789. We then use the currency pipe to format the price variable as a currency value in the template.
The first usage of the pipe is with the default settings. It will format the price variable with the default currency of the current locale.
The second usage of the pipe includes some additional parameters. It formats the price variable with the EUR currency symbol, a narrow symbol, and a format string of 4.2-2. The format string indicates that the number should have a minimum of 4 digits before the decimal separator, a maximum of 2 digits after the decimal separator, and should use the locale's decimal and grouping separators.
When the above code is run, it will display the following output:
Using CurrencyPipe
Price: $12,345.68
Price: €12,345.68
The first output line shows the default formatted currency value for the current locale. The second output line shows a custom-formatted currency value with the Euro currency symbol, a narrow symbol, and a specific format string.
2. Date Pipe
DatePipeis a built-in pipe in Angular that is used to format a date object.
It provides a way to display date values in a user-friendly format based on the current locale.
Here’s an example of how to use the DatePipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentDate: Date = new Date();
}
app.component.html:
<div>
<h2>Using DatePipe</h2>
<p>Current date: {{ currentDate | date }}</p>
<p>Current date: {{ currentDate | date:'fullDate' }}</p>
<p>Current date: {{ currentDate | date:'short' }}</p>
</div>
In the above example, we have a currentDate variable that holds the current date object. We then use the date pipe to format the currentDate variable as a date value in the template.
The first usage of the pipe is with the default settings. It will format the currentDate variable with the default date format of the current locale.
The second usage of the pipe includes a format string of fullDate. This will format the currentDate variable as a full date string, such as "Tuesday, March 8, 2022".
The third usage of the pipe includes a format string of short. This will format the currentDate variable as a short date string, such as "3/8/22".
When the above code is run, it will display the following output:
Using DatePipe
Current date: Mar 3, 2023
Current date: Friday, March 3, 2023
Current date: 3/3/23, 12:17 AM
The first output line shows the default formatted date value for the current locale. The second output line shows the currentDate variable formatted as a full date string. The third output line shows the currentDate variable formatted as a short date string.
3. Json Pipe
JsonPipeis a built-in pipe in Angular that is used to transform an object into a JSON string.
It provides a way to display object values in a formatted JSON string.
Here’s an example of how to use the JsonPipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myObject: any = {
name: 'John',
age: 30,
email: 'john@example.com'
};
}
app.component.html:
<div>
<h2>Using JsonPipe</h2>
<pre>{{ myObject | json }}</pre>
</div>
In the above example, we have a myObject variable that holds an object with a name, age, and email property. We then use the json pipe to transform the myObject variable into a JSON string.
The pre tag is used to preserve white spaces and formatting in the output.
When the above code is run, it will display the following output:
Using JsonPipe
{
"name": "John",
"age": 30,
"email": "john@example.com"
}
The output shows the myObject variable transformed into a JSON string with formatted white spaces. This can be useful for debugging and displaying object values in a readable format.
4. LowerCase Pipe
LowerCasePipeis a built-in pipe in Angular that is used to transform a string into alowercasedstring.
Here’s an example of how to use the LowerCasePipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myString: string = 'This is a STRING in Mixed CASE';
}
app.component.html:
<div>
<h2>Using LowerCasePipe</h2>
<p>Original String: {{ myString }}</p>
<p>Lowercased String: {{ myString | lowercase }}</p>
</div>
In the above example, we have a myString variable that holds a string value in mixed case. We then use the lowercase pipe to transform the myString variable into a lowercased string.
When the above code is run, it will display the following output:
Using LowerCasePipe
Original String: This is a STRING in Mixed CASE
Lowercased String: this is a string in mixed case
The first output line shows the original string value. The second output line shows the transformed string value after using the lowercase pipe. Note that all characters in the string have been transformed to lowercase.
5. UpperCase Pipe
UpperCasePipeis a built-in pipe in Angular that is used to transform a string into an uppercased string.
Here’s an example of how to use the UpperCasePipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myString: string = 'This is a STRING in Mixed CASE';
}
app.component.html:
<div>
<h2>Using UpperCasePipe</h2>
<p>Original String: {{ myString }}</p>
<p>Uppercased String: {{ myString | uppercase }}</p>
</div>
In the above example, we have a myString variable that holds a string value in mixed case. We then use the uppercase pipe to transform the myString variable into an uppercased string.
When the above code is run, it will display the following output:
Using UpperCasePipe
Original String: This is a STRING in Mixed CASE
Uppercased String: THIS IS A STRING IN MIXED CASE
The first output line shows the original string value. The second output line shows the transformed string value after using the uppercase pipe. Note that all characters in the string have been transformed to uppercase.
5. Percent Pipe
PercentPipeis a built-in pipe in Angular that is used to transform a number into a percent value.
Here’s an example of how to use the PercentPipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myNumber: number = 0.23;
}
app.component.html:
<div>
<h2>Using PercentPipe</h2>
<p>Original Number: {{ myNumber }}</p>
<p>Percentage Value: {{ myNumber | percent }}</p>
</div>
In the above example, we have a myNumber variable that holds a number value. We then use the percent pipe to transform the myNumber variable into a percentage value.
When the above code is run, it will display the following output:
Using PercentPipe
Original Number: 0.23
Percentage Value: 23%
The first output line shows the original number value. The second output line shows the transformed percentage value after using the percent pipe. Note that the decimal value is multiplied by 100 and a percentage sign is added to the end of the value.
6. Slice Pipe
SlicePipe is a built-in pipe in Angular that is used to create a new array or string that contains a portion of an existing array or string.
Here’s an example of how to use the SlicePipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myArray: any[] = ['apple', 'banana', 'orange', 'grape', 'mango'];
myString: string = 'This is a long string.';
}
app.component.html:
<div>
<h2>Using SlicePipe on Array</h2>
<p>Original Array: {{ myArray }}</p>
<p>Sliced Array: {{ myArray | slice:1:3 }}</p>
</div>
<div>
<h2>Using SlicePipe on String</h2>
<p>Original String: {{ myString }}</p>
<p>Sliced String: {{ myString | slice:0:7 }}</p>
</div>
In the above example, we have a myArray variable that holds an array of fruits and a mySecodString variable that holds a string value. We then use the slice pipe to create a new array or string that contains a portion of the original array or string.
When the above code is run, it will display the following output:
Using SlicePipe on Array
Original Array: apple,banana,orange,grape,mango
Sliced Array: banana,orange
Using SlicePipe on String
Original String: This is a long string.
Sliced String: This is
The first output section shows the original array value and the sliced array value using the slice pipe. Note that the slice starts from index 1 and ends at index 3, which means that the sliced array will contain the elements at index 1 and index 2 (not including index 3). The second output section shows the original string value and the sliced string value using the slice pipe. Note that the slice starts from index 0 and ends at index 7, which means that the sliced string will contain the characters at index 0 to index 6 (not including index 7).
7. TitleCase Pipe
TitleCasePipeis a built-in pipe in Angular that is used to transform a string into a title case, which means the first letter of each word is capitalized.
Here’s an example of how to use the TitleCasePipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: './app.component.html'
})
export class AppComponent {
myString: string = 'this is a sentence in lowercase.';
}
In the above example, we have a myString variable that holds a string value. We then use the titlecase pipe to transform the myString variable into a title case.
<h2>Using TitleCasePipe</h2>
<p>Original String: {{ myString }}</p>
<p>Transformed String: {{ myString | titlecase }}</p>
When the above code is run, it will display the following output:
Using TitleCasePipe
Original String: this is a sentence in lowercase.
Transformed String: This Is A Sentence In Lowercase.
The first output line shows the original string value. The second output line shows the transformed title case value after using the titlecase pipe.
Note that the first letter of each word is capitalized.
8. Async Pipe
AsyncPipe is a built-in pipe in Angular that is used to handle asynchronous data streams. It is commonly used to subscribe to observables or promises and display the emitted values in the view.
Here’s an example of how to use the AsyncPipe in Angular:
app.component.ts:
import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-root',
template: './app.component.html'
})
export class AppComponent {
myObservable$: Observable<number> = of(42);
myPromise$: Promise<string> = Promise.resolve('Hello World!');
}
In the above example, we have a myObservable$ variable that holds an observable that emits the number 42. We also have a myPromise$ variable that holds a promise that resolves to the string Hello World!. We then use the async pipe to subscribe to these observables and promises and display the emitted values in the view.
When the above code is run, it will display the following output:
<h2>Using AsyncPipe with Observable</h2>
<p>{{ myObservable$ | async }}</p>
<h2>Using AsyncPipe with Promise</h2>
<p>{{ myPromise$ | async }}</p>
Using AsyncPipe with Observable
42
Using AsyncPipe with Promise
Hello World!
The first output section shows the value emitted by the observable using the async pipe. The second output section shows the value resolved by the promise using the async pipe. Note that the async pipe automatically subscribes to the observables and promises and unsubscribes when the component is destroyed to prevent memory leaks.
Built in pipes
By defining a new class and implementing the PipeTransform interface, you can create custom pipes in Angular. There is only one method in the PipeTransform interface called transform, which accepts an input value and outputs the transformed value.
custom.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'filterByLength'})
export class CustomPipe implements PipeTransform {
transform(values: string[], minLength: number): string[] {
return values.filter(value => value.length >= minLength);
}
}
We define a CustomPipe class in the example above, and it implements the PipeTransform interface. Two parameters are required for the transform() method: a minimum length and an array of strings. The strings in the array that are longer than or equal to the given length are then filtered out.
Next, we give the pipe a name by adding a name property and decorating the class with the @Pipe decorator. In our templates, we'll refer to the pipe by its name.
app.module.ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { CustomPipe } from "./custom.pipe";
import { AppComponent } from "./app.component";
@NgModule({
declarations: [AppComponent, CustomPipe],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: './app.component.html'
})
export class AppComponent {
values: string[] = ['apple', 'banana', 'carrot', 'date'];
}
<h2>Using Custom Pipe</h2>
<ul>
<li *ngFor="let value of values | filterByLength: 5">{{ value }}</li>
</ul>
In the above example, we have a values array that contains some strings. We then use the filterByLength pipe to filter out any strings that are shorter than 5 characters. We use the *ngFor directive to loop through the filtered values and display them in an unordered list.
When the above code is run, it will display the following output:
Using Custom Pipe
apple
banana
carrot
The output shows the two strings from the values array that are longer than or equal to 5 characters.
REFERENCE: https://medium.com/@aqeelabbas3972/pipes-in-angular-6a871589299d