Angular Built-in Pipes: Date, Currency, and JSON
Angular provides a variety of built-in pipes that help transform data for display purposes within templates. Among these, the Date
, Currency
, and JSON
pipes are particularly useful for formatting and presenting data in a user-friendly manner. Let's dive into each of these pipes in detail, providing important information and examples.
1. Date Pipe
The Date
pipe is used to format a given date according to locale rules. It converts a Date
object or a string representing a date into a human-readable form based on specified format strings or locale-specific rules.
Syntax:
{{ date_expression | date : format : timezone : locale }}
date_expression
: The date to be formatted.format
: Optional. The date format string (defaults tomediumDate
).timezone
: Optional. The timezone ID string (default is local timezone). Possible values are: 'UTC' and any IANA compatible timezone ID.locale
: Optional. The locale ID.
Examples:
<p>Default format: {{ today | date }}</p> <!-- June 15, 2023 -->
<p>Full date and time: {{ today | date:"fullDate 'at' shortTime" }}</p> <!-- Thursday, June 15, 2023 at 10:45 AM -->
<p>ISO format: {{ today | date:"yyyy-MM-ddTHH:mm:ss" }}</p> <!-- 2023-06-15T10:45:00 -->
<p>Only month and day: {{ today | date:"MMMM d" }}</p> <!-- June 15 -->
Predefined Format Options:
short
: equivalent toM/d/yy, h:mm a
(6/15/23, 10:45 AM)medium
: equivalent toMMM d, y, h:mm:ss a
(Jun 15, 2023, 10:45:05 AM)long
: equivalent toMMMM d, y, h:mm:ss a z
(June 15, 2023, 10:45:05 AM GMT-05:00)full
: equivalent toEEEE, MMMM d, y, h:mm:ss a zzzz
(Thursday, June 15, 2023, 10:45:05 AM GMT-05:00 Eastern Daylight Time)shortDate
: equivalent toM/d/yy
(6/15/23)mediumDate
: equivalent toMMM d, y
(Jun 15, 2023)longDate
: equivalent toMMMM d, y
(June 15, 2023)fullDate
: equivalent toEEEE, MMMM d, y
(Thursday, June 15, 2023)shortTime
: equivalent toh:mm a
(10:45 AM)mediumTime
: equivalent toh:mm:ss a
(10:45:05 AM)longTime
: equivalent toh:mm:ss a z
(10:45:05 AM GMT-05:00)fullTime
: equivalent toh:mm:ss a zzzz
(10:45:05 AM GMT-05:00 Eastern Daylight Time)
2. Currency Pipe
The Currency
pipe transforms a number to a currency string, formatted according to locale rules. It's useful for displaying monetary values with correct denominations and symbols.
Syntax:
{{ value | currency : code : list : digitsInfo : locale }}
value
: The number to be formatted as currency.code
: Optional. Three-letter ISO 4217 currency code (default isUSD
).display
: Optional. Controls how the currency code or symbol is displayed (code
|symbol
|symbol-narrow
|string
).digitsInfo
: Optional. Decimal representation options, such as minimum and maximum number of digits (x.y-z
).locale
: Optional. Locale ID.
Examples:
<p>Default currency: {{ price | currency }}</p> <!-- $2,314.50 -->
<p>Euro currency: {{ price | currency:"EUR" }}</p> <!-- € 2,314.50 -->
<p>Indian Rupees with symbol: {{ price | currency:"INR":'symbol-narrow':'1.2-2' }}</p> <!-- ₹2,314.50 -->
<p>US Dollars with full currency name: {{ price | currency:"USD":'string':'3.2-2':'en-US' }}</p> <!-- USD 2,314.50 -->
Display Options:
code
: Use ISO currency code (e.g., USD).symbol
(default): Use currency symbol (e.g., $).symbol-narrow
: Use narrow currency symbol (e.g., $).string
: Use the full name of the currency (e.g., US Dollars).
Digits Info:
- Also applicable to the
number
pipe, this format specifies how many digits are shown. For instance,1.2-2
specifies at least one integer digit and two to two decimal digits.
3. JSON Pipe
The JSON
pipe is used to convert a JavaScript object or array into a JSON string. It's helpful for debugging purposes or when you need to display structured data in a template.
Syntax:
{{ object_or_array | json }}
object_or_array
: The object or array to be converted to JSON format.
Example:
<p>Object as JSON: {{ user | json }}</p> <!-- {"name":"John","age":30,"email":"john@example.com"} -->
Usage Details:
- The
JSON
pipe is particularly useful for debugging, as it provides a human-readable string representation of the object or array. - It formats the JSON with indentation for better readability.
Conclusion
Angular's built-in Date
, Currency
, and JSON
pipes provide essential functionalities that simplify data presentation in templates. Understanding how to use these pipes effectively can significantly enhance the user experience by ensuring that dates are displayed according to locale rules, currencies are presented with appropriate symbols, and complex data structures are understandable and debuggable.
By mastering these pipes, developers can create more polished and user-friendly applications with less code and fewer custom solutions.
Examples, Set Route and Run the Application Then Data Flow Step by Step for Beginners
Topic: Angular Built-in Pipes - Date, Currency, Json
Welcome to a detailed guide on how to use Angular built-in pipes such as DatePipe
, CurrencyPipe
, and JsonPipe
in your projects. In this tutorial, we will walk through setting up a basic Angular project, configuring routes, using these pipes, and understanding the data flow. This is intended for beginners who are new to Angular and need a hands-on introduction.
Step 1: Setting Up an Angular Project
Before we dive into using the pipes, let's start by setting up an Angular project. We will use the Angular CLI for this purpose.
a) Install Angular CLI
First, you'll need Node.js and NPM installed on your system. Then install Angular CLI globally:
npm install -g @angular/cli
Verify the installation by checking its version:
ng version
b) Create a New Angular Project
Next, create a new Angular project:
ng new angular-pipes-example --routing=true
This command creates an Angular project named angular-pipes-example
and includes routing (--routing=true
).
Navigate to the newly created project:
cd angular-pipes-example
Serve the app with:
ng serve
Open your browser and navigate to http://localhost:4200/
. You should see the default home page of your Angular app.
Step 2: Configuring Routes
Now that our project is initialized and running, we'll configure routes to set up different components for each pipe example: date
, currency
, and json
.
In the src/app/
directory, create three new components:
ng generate component date-demo
ng generate component currency-demo
ng generate component json-demo
These commands will generate three directories, each containing the component files, and add them to the declarations array within app.module.ts
.
Next, let’s define our routes in app-routing.module.ts
:
// src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DateDemoComponent } from './date-demo/date-demo.component';
import { CurrencyDemoComponent } from './currency-demo/currency-demo.component';
import { JsonDemoComponent } from './json-demo/json-demo.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: DateDemoComponent },
{ path: 'currency', component: CurrencyDemoComponent },
{ path: 'json', component: JsonDemoComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
We have defined two additional paths /currency
and /json
, with their respective components.
Step 3: Creating Links in the Navigation Bar
Now let's create some links in the navigation bar to navigate between these components. Open the app.component.html
and update it as follows:
<!-- src/app/app.component.html -->
<nav>
<a routerLink="/home">Date</a>
<a routerLink="/currency">Currency</a>
<a routerLink="/json">Json</a>
</nav>
<router-outlet></router-outlet>
The <router-outlet>
directive acts as a placeholder where routed components are loaded.
Step 4: Using Date Pipe
Let’s start with the DatePipe
. It is used to format dates into local time based on the given locale.
Update date-demo.component.ts
:
// src/app/date-demo/date-demo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-date-demo',
templateUrl: './date-demo.component.html',
styleUrls: ['./date-demo.component.css']
})
export class DateDemoComponent {
currentDate: Date;
constructor() {
this.currentDate = new Date();
}
}
Create a simple template in date-demo.component.html
to display the date:
<!-- src/app/date-demo/date-demo.component.html -->
<p>Today's date:</p>
<p>{{ currentDate | date }}</p>
<p>Date format - Short Date:</p>
<p>{{ currentDate | date:'shortDate' }}</p>
<p>Date format - Full Date:</p>
<p>{{ currentDate | date:'fullDate' }}</p>
<p>Date format - ISO Date:</p>
<p>{{ currentDate | date:'yyyy-MM-ddTHH:mm:ss' }}</p>
Angular provides different predefined date formats like shortDate
, medium
, and custom formats.
Step 5: Using Currency Pipe
The CurrencyPipe
transforms numbers to currency strings based on the user's locale or provided locale.
Update currency-demo.component.ts
:
// src/app/currency-demo/currency-demo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-currency-demo',
templateUrl: './currency-demo.component.html',
styleUrls: ['./currency-demo.component.css']
})
export class CurrencyDemoComponent {
price: number = 25.99;
currencyCode: string = 'USD';
}
Set up the currency-demo.component.html
:
<!-- src/app/currency-demo/currency-demo.component.html -->
<p>Price of the item in US Dollars:</p>
<p>{{ price | currency:currencyCode:'symbol':'1.2-2':'en-US' }}</p>
<p>German Equivalent:</p>
<p>{{ price | currency:currencyCode:'symbol':'1.2-2':'de-DE' }}</p>
Here, 'symbol'
means we want to show the currency symbol, '1.2-2'
represents significant digits formatting, and 'en-US'
or 'de-DE'
defines the locales.
Step 6: Using JSON Pipe
Lastly, the JsonPipe
is useful for viewing object content when debugging.
Update json-demo.component.ts
:
// src/app/json-demo/json-demo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-json-demo',
templateUrl: './json-demo.component.html',
styleUrls: ['./json-demo.component.css']
})
export class JsonDemoComponent {
product: any = {
name: 'Laptop',
price: 999.99,
features: ['High resolution screen', '8GB RAM', '256GB SSD'],
available: true
};
}
Display the JSON data in the json-demo.component.html
:
<!-- src/app/json-demo/json-demo.component.html -->
<p>Product details in JSON:</p>
<pre>{{ product | json }}</pre>
Step 7: Running the Application and Understanding Data Flow
After creating and updating these components, make sure everything is saved, and navigate back to your terminal.
Run the application with:
ng serve
Visit localhost:4200
in your browser. Here are the steps you should take:
- Click on "Date" - see the current date displayed in various formats.
- Click on "Currency" - see the same price displayed differently in two different currencies.
- Click on "Json" - view the product object printed as a JSON string.
When you click these links, Angular uses the configured routes in AppRoutingModule
to render the respective component at the <router-outlet>
place. The data is passed into components' classes (.ts
files), which can be directly used in the templates (.html
) thanks to Angular’s two-way data binding and templating capabilities.
Understanding Data Flow:
Data Binding: Angular automatically binds data from the
component.ts
file to thecomponent.html
file, enabling us to use properties directly in the HTML templates.Template Syntax: We use Angular’s template syntax with curly braces to invoke pipes and transform data accordingly. Each pipe is followed by a colon and additional parameters can be added.
Routing: When a user clicks on a link, Angular triggers the route change mechanism. It looks up the path in
app-routing.module.ts
, finds the corresponding component, and renders it in the<router-outlet>
.
That concludes our beginner-friendly tutorial on using DatePipe
, CurrencyPipe
, and JsonPipe
in Angular. These pipes form the core transformation utilities that make Angular extremely powerful for building internationalized apps. Practice using these pipes in different contexts, and you’ll be well on your way towards mastering Angular’s built-in capabilities!
Certainly! Angular’s built-in pipes provide powerful data transformation capabilities directly within the HTML templates, making your application cleaner and more maintainable. Below are ten questions and their answers related to the date
, currency
, and json
pipes in Angular.
1. What is a pipe in Angular and how does it work?
Answer: A pipe in Angular is a class that implements the pipe transformation logic in its transform
method. Pipes are used to format strings, currency amounts, dates, and other display data. Angular provides several built-in pipes, including DatePipe
, CurrencyPipe
, and JsonPipe
. These can be utilized to modify values before rendering them in views, allowing for cleaner template markup without the need for extensive logic in controllers or components.
2. How do you use the DatePipe
to format a date in an Angular template?
Answer: The DatePipe
allows you to format a Date object or a valid date string in Angular templates. You can specify the format, locale, and timezone if needed. Here’s an example:
<p>{{ currentDate | date:'yyyy-MM-dd' }}</p> <!-- Outputs the date in YYYY-MM-DD format -->
In this example, currentDate
is a variable holding a Date object or a valid date string, and the date:
part is used to format it according to the specified pattern ('yyyy-MM-dd'
). Other common patterns include 'fullDate'
, 'shortTime'
, etc.
3. What are the default formatting options available with the DatePipe
?
Answer: The DatePipe
offers several predefined formats:
'medium'
(default) - e.g., Jan 8, 2022, 5:03:45 PM'short'
- e.g., 1/8/22, 5:03 PM'long'
- e.g., January 8, 2022 at 5:03:45 PM CST'fullDate'
- e.g., Sunday, January 8, 2022'fullTime'
- e.g., 5:03:45 PM Central Standard Time'basicDate'
- e.g., 20220108'basicDateTime'
- e.g., 20220108T170345.000
These can be selected by passing just the name of the format as a string to the pipe in your template.
4. How do you format a date with custom patterns using the DatePipe
?
Answer: Custom date patterns can be defined using characters like y
, M
, d
, h
, H
, s
, a
, and more, which represent parts of the date and time. Here are some examples:
<p>{{ currentDate | date:'dd-MMM-yyyy' }}</p> <!-- Output: 08-Jan-2022 -->
<p>{{ currentDate | date:'HH:mm:ss Z' }}</p> <!-- Output: 17:03:45 +0500 -->
<p>{{ currentDate | date:'EEEE, MMM d, y h:mm:ss a zzzz' }}</p> <!-- Output: Sunday, Jan 8, 2022 5:03:45 PM Central Standard Time -->
Each character in the pattern corresponds to a specific part of the date or time, allowing for highly customized outputs.
5. How can I change the locale for the DatePipe
in Angular?
Answer: To change the locale for the DatePipe
, you must import the desired locale module into your application's root module (typically app.module.ts
). For example, to set the locale to German (Germany):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';
// Import the German locale
import localeDeDe from '@angular/common/locales/de';
import { registerLocaleData } from '@angular/common';
// Register the locale data
registerLocaleData(localeDeDe);
Then, update the component template to use the locale
parameter with the DatePipe
.
<p>{{ currentDate | date:'fullDate':'GMT':'de' }}</p>
This will render the full date string in the German locale.
6. Explain the usage of the CurrencyPipe
in an Angular template.
Answer: The CurrencyPipe
formats a number to a currency string based on the selected locale. It allows you to specify the currency code, display style (symbol, narrow, code, name), minimum integer digits, minimum and maximum fraction digits, and locale. Here’s an example:
<p>{{ totalAmount | currency:'USD':'symbol':'1.2-2' }}</p>
In this example, totalAmount
is a numeric value representing the amount in USD. The 'symbol'
specifies that the currency symbol should be displayed (e.g., $
). '1.2-2'
indicates that the output should have at least one digit before the decimal and two to two digits after the decimal.
7. Can the CurrencyPipe
support different currencies dynamically?
Answer: Yes, the CurrencyPipe
can accept a currency code dynamically via a bound component property:
<p *ngIf="exchangeRate && selectedCurrency">{{ totalAmount * exchangeRate | currency:selectedCurrency }}</p>
Here, selectedCurrency
is a string representing the ISO currency code (e.g., 'EUR'). This allows you to flexibly handle multiple currencies within the same template.
8. How do you ensure the CurrencyPipe
displays the appropriate decimal places for different currencies?
Answer: Most currencies have established conventions for decimal places, but these can be overridden by specifying minimum and maximum fraction digits explicitly. For instance:
<p>{{ 1234.5678 | currency:'EUR':'symbol':'1.0-0' }}</p> <!-- Renders as: €1,235 -->
In this example, the pipe will round the number and only show zero decimal places despite the original value having more.
9. What is the purpose of the JsonPipe
and how does it work?
Answer: The JsonPipe
is used to convert JavaScript objects into JSON strings for display. This is particularly useful for debugging purposes, such as displaying the contents of an array or object directly in the browser:
<pre>{{ userObject | json }}</pre>
Here, userObject
could be any complex data structure. Using the JsonPipe
will convert this object into a formatted JSON string suitable for reading. Note that this should generally be avoided in production environments due to performance and security concerns.
10. Are Angular pipes impure by default? Explain the difference between pure and impure pipes.
Answer: No, Angular built-in pipes, including DatePipe
, CurrencyPipe
, and JsonPipe
, are pure by default. Pure pipes are only re-executed when their input values change. Impure pipes, on the other hand, run on every change detection cycle.
Pure Pipe: A pure pipe checks whether the input has changed based on reference equality (==) for primitives like numbers or strings) or by object comparison for complex types (i.e., whether references have changed). If the pipe detects a difference, it recalculates its output.
Impure Pipe: An impure pipe is always called, regardless of whether the input has changed, because impure pipes cannot determine whether the input has changed or not without manually checking all properties. They are useful when you want a pipe to execute frequently, like
AsyncPipe
for asynchronous operations.
Example of impure pipe (though none of the mentioned pipes are impure):
@Pipe({
name: 'custom',
pure: false // Declaring it as impure
})
export class CustomPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
// Impure transformation logic here
}
}
Using pipes wisely ensures optimal performance by reducing unnecessary computations.
Understanding the usage and nuances of Angular's built-in pipes like DatePipe
, CurrencyPipe
, and JsonPipe
enhances your ability to create well-formatted and maintainable views. Remember to tailor these tools to fit the needs of your specific application, especially regarding locales and currency conventions.