Angular Builtin Pipes Date Currency Json Complete Guide
Understanding the Core Concepts of Angular Builtin Pipes date, currency, json
Date Pipe
The date
pipe formats date values to a specified format. This is particularly useful when you want to display dates in a human-readable form.
Syntax
{{ value_expression | date[:format[:timezone[:locale]]] }}
Parameters
value_expression
: The date to be formatted, which can be aDate
object, a number (milliseconds since UTC epoch), or an ISO string.format
: The format string according to Angular's date formatting rules. If omitted, the default format of'mediumDate'
is used.timezone
: (optional) The time zone in which to format the date. It can be a string representing the timezone ID (e.g., "UTC") or an offset from GMT (e.g., "+0430").locale
: (optional) Locale ID (e.g., 'en-US') to format the date according to locale rules.
Common Format Options
'short'
: equivalent to'M/d/yy, h:mm a'
(12/15/15, 9:30 AM)'medium'
: equivalent to'MMM d, y, h:mm:ss a'
(Dec 15, 2015, 9:30:45 AM)'long'
: equivalent to'MMMM d, y, h:mm:ss a z'
(December 15, 2015 at 9:30:45 AM GMT+1)'full'
: equivalent to'EEEE, MMMM d, y, h:mm:ss a zzzz'
(Tuesday, December 15, 2015 at 9:30:45 AM GMT+01:00)'shortDate'
: equivalent to'M/d/yy'
(12/15/15)'mediumDate'
: equivalent to'MMM d, y'
(Dec 15, 2015)'longDate'
: equivalent to'MMMM d, y'
(December 15, 2015)'fullDate'
: equivalent to'EEEE, MMMM d, y'
(Tuesday, December 15, 2015)'shortTime'
: equivalent to'h:mm a'
(9:30 AM)'mediumTime'
: equivalent to'h:mm:ss a'
(9:30:45 AM)'longTime'
: equivalent to'h:mm:ss a z'
(9:30:45 AM GMT+1)'fullTime'
: equivalent to'h:mm:ss a zzzz'
(9:30:45 AM GMT+01:00)
Example
<p>{{ today | date:'fullDate' }}</p> <!-- Tuesday, December 15, 2020 -->
<p>{{ today | date:'short' }}</p> <!-- 12/15/20, 8:30 AM -->
<p>{{ today | date:'shortDate' }}</p> <!-- 12/15/20 -->
<p>{{ today | date:'shortTime' }}</p> <!-- 8:30 AM -->
Currency Pipe
The currency
pipe transforms numbers to currency strings, allowing for customization of currency symbol, locale, and fraction digits.
Syntax
{{ value_expression | currency[:currencyCode[:display[:digitsInfo[:locale]]]] }}
Parameters
value_expression
: The number to be formatted.currencyCode
: The ISO 4217 currency code, such as 'USD'. Default is 'USD'.display
: (optional) Controls the display pattern. Can be one of:'code'
: Displays the currency as an ISO 4217 currency code (e.g., USD).'symbol'
: Displays the currency as a currency symbol (e.g., $).'symbol-narrow'
: Display the currency symbol in the narrow form (e.g., $).'string'
: Display the currency as a string (e.g., 'US dollars').
digitsInfo
: (optional) Decimal representations (e.g.,3.1-2
).locale
: (optional) Locale ID (e.g., 'en-US') to format the currency according to locale rules.
Example
<p>{{ amount | currency:'USD':'symbol':'3.2-2' }}</p> <!-- $2,500.00 -->
<p>{{ amount | currency:'EUR':'symbol' }}</p> <!-- €2,500 -->
<p>{{ amount | currency:'EUR':'symbol-narrow' }}</p> <!-- €2,500 -->
<p>{{ amount | currency:'JPY' }}</p> <!-- ¥2,500 -->
<p>{{ amount | currency:'GBP':'code' }}</p> <!-- GBP 2,500.00 -->
JSON Pipe
The json
pipe converts a JavaScript object or value to a JSON string. While it may not be used frequently in production code due to performance implications, it is invaluable during development for debugging purposes.
Syntax
Online Code run
Step-by-Step Guide: How to Implement Angular Builtin Pipes date, currency, json
Prerequisites:
- Node.js installed on your system.
- Angular CLI (
npm install -g @angular/cli
) installed. - Basic knowledge of HTML, CSS, and TypeScript.
Step 1: Create a New Angular Application
Open your terminal or command prompt and run the following command to create a new Angular application:
ng new angular-pipes-demo
cd angular-pipes-demo
Step 2: Generate a New Component
Next, generate a new component where we will use the pipes:
ng generate component pipe-examples
This will create a new folder under src/app
named pipe-examples
, and it will contain several files for the component.
Step 3: Open the Component File
Navigate to src/app/pipe-examples/pipe-examples.component.ts
and open it in your text editor. Update the component class as follows:
import { Component } from '@angular/core';
@Component({
selector: 'app-pipe-examples',
templateUrl: './pipe-examples.component.html',
styleUrls: ['./pipe-examples.component.css']
})
export class PipeExamplesComponent {
todayDate: Date = new Date();
amount: number = 1500.75;
objectExample: any = {name: "John Doe", age: 30, city: "New York"};
constructor() {}
}
Step 4: Update the Component Template
Navigate to src/app/pipe-examples/pipe-examples.component.html
and open it. Let’s add some HTML to demonstrate the use of the pipes:
Using date
Pipe
The date
pipe allows you to format dates based on specific patterns.
<h2>Date Pipe Example</h2>
<p>Default Format: {{todayDate | date}}</p>
<p>Full Date (with long name): {{todayDate | date:'fullDate'}}</p>
<p>Medium Date Format: {{todayDate | date:'medium'}}</p>
<p>Short Date Format: {{todayDate | date:'short'}}</p>
<p>Custom Date Format (dd/MM/yyyy): {{todayDate | date:'dd/MM/yyyy'}}</p>
Using currency
Pipe
The currency
pipe formats a number to a currency string.
<h2>Currency Pipe Example</h2>
<p>Default Currency: {{amount | currency}}</p>
<p>US Dollar (USD): {{amount | currency:'USD'}}</p>
<p>Euro (EUR) with code: {{amount | currency:'EUR':'symbol-narrow'}}</p>
<p>Pound Sterling (GBP) without space between symbol and value: {{amount | currency:'GBP':'symbol':'0.0-0'}}</p>
Using json
Pipe
The json
pipe converts an object into its JSON representation.
<h2>JSON Pipe Example</h2>
<p>Original Object Data:</p>
<pre>{{objectExample}}</pre>
<p>JSON Formatted Data:</p>
<pre>{{objectExample | json}}</pre>
Step 5: Add the Component to Your App
Now, let’s ensure that our component shows up in the application. Open the main app component file located at src/app/app.component.html
and add the selector for our PipeExamplesComponent
:
<app-pipe-examples></app-pipe-examples>
Step 6: Serve and Run the Application
Finally, serve your application by running the following command in your terminal:
ng serve
Navigate to http://localhost:4200/
in your web browser. You should see the following:
- Date Pipe Example displaying the current date in different formats.
- Currency Pipe Example showing the amount in various currencies.
- JSON Pipe Example presenting the JSON representation of an object.
Full Code Summary
pipe-examples.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-pipe-examples',
templateUrl: './pipe-examples.component.html',
styleUrls: ['./pipe-examples.component.css']
})
export class PipeExamplesComponent {
todayDate: Date = new Date();
amount: number = 1500.75;
objectExample: any = {name: "John Doe", age: 30, city: "New York"};
constructor() {}
}
pipe-examples.component.html
<h2>Date Pipe Example</h2>
<p>Default Format: {{todayDate | date}}</p>
<p>Full Date (with long name): {{todayDate | date:'fullDate'}}</p>
<p>Medium Date Format: {{todayDate | date:'medium'}}</p>
<p>Short Date Format: {{todayDate | date:'short'}}</p>
<p>Custom Date Format (dd/MM/yyyy): {{todayDate | date:'dd/MM/yyyy'}}</p>
<h2>Currency Pipe Example</h2>
<p>Default Currency: {{amount | currency}}</p>
<p>US Dollar (USD): {{amount | currency:'USD'}}</p>
<p>Euro (EUR) with code: {{amount | currency:'EUR':'symbol-narrow'}}</p>
<p>Pound Sterling (GBP) without space between symbol and value: {{amount | currency:'GBP':'symbol':'0.0-0'}}</p>
<h2>JSON Pipe Example</h2>
<p>Original Object Data:</p>
<pre>{{objectExample}}</pre>
<p>JSON Formatted Data:</p>
<pre>{{objectExample | json}}</pre>
app.component.html
<app-pipe-examples></app-pipe-examples>
Conclusion
You have now successfully created a simple Angular application demonstrating the use of Angular's built-in pipes such as date
, currency
, and json
.
Top 10 Interview Questions & Answers on Angular Builtin Pipes date, currency, json
1. What is the date
pipe in Angular, and how does it format dates?
Answer:
The date
pipe in Angular is used to format a given date to a specific string pattern. The syntax includes a date expression and an optional format string. Commonly used format strings include:
'medium'
(default): e.g.,Sep 3, 2010, 12:05:08 PM
'short'
: e.g.,9/3/10, 12:05 PM
'fullDate'
: e.g.,September 3, 2010
'longDate'
: e.g.,Sep 3, 2010
'shortDate'
: e.g.,9/3/10
'mediumTime'
: e.g.,12:05:08 PM
'shortTime'
: e.g.,12:05 PM
Example:
<p>{{ today | date:'medium' }}</p> <!-- Outputs: Sep 3, 2010, 12:05:08 PM -->
2. How does the currency
pipe format numbers as currency in Angular?
Answer:
The currency
pipe is used to format a number as currency, taking into account a given currency code, symbol display, and decimal notation. The basic syntax is:
{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}
currencyCode
: The ISO 4217 currency code (e.g., 'USD', 'EUR').display
: How to display the currency symbol ('code', 'symbol', 'symbol-narrow') or whether to hide it ('string').digitsInfo
: Decimal precision (e.g., '1.2-4').locale
: Optional locale code (e.g., 'en-US').
Example:
<p>{{ amount | currency:'USD':'symbol' }}</p> <!-- Outputs: $1,234.56 -->
3. How do you use the json
pipe to convert an object into a JSON string in Angular?
Answer:
The json
pipe formats an object into a JSON string. This is particularly useful for debugging to display the JSON structure of complex data objects directly on the DOM.
Example:
<pre>{{ user | json }}</pre>
<!-- Outputs: {"name":"John Doe","age":28,"email":"john.doe@example.com"} -->
4. Can you customize the date
pipe's output to include only the month and day?
Answer:
Yes, you can customize the date
pipe's output using format strings to include only the month and day:
'MM/dd'
: Numeric date (including leading zero)'MMM d'
: Abbreviated textual month and day'MMMM d'
: Full textual month and day
Example:
<p>{{ today | date:'MMM d' }}</p> <!-- Outputs: Sep 3 -->
5. How can you change the locale for localization in Angular pipes like date
and currency
?
Answer:
To change the locale, you need to import the locale data and set it in your app module using LOCALE_ID
:
Install the locale:
npm install @angular/common/locales/LOCALE_CODE
Import the locale data:
import localeEs from '@angular/common/locales/es';
Register the locale with the
registerLocaleData
function:import { registerLocaleData } from '@angular/common'; registerLocaleData(localeEs);
Set the
LOCALE_ID
provider:import { LOCALE_ID, NgModule } from '@angular/core'; @NgModule({ providers: [ { provide: LOCALE_ID, useValue: 'es' } ], }) export class AppModule { }
Example:
<p>{{ today | date:'fullDate':'':'es' }}</p> <!-- Outputs: viernes, 3 de septiembre de 2010 -->
6. What happens if a value passed to the currency
pipe is not a number?
Answer:
If a non-numeric value is passed to the currency
pipe, Angular will attempt to parse it to a number. If parsing fails, it will return the original value, likely resulting in an unexpected formatted string.
Example:
<p>{{ 'not-a-number' | currency:'USD' }}</p> <!-- Outputs: not-a-number -->
7. Can the date
pipe be used to extract just the year or just the time from a date object?
Answer:
Yes, you can extract just the year or the time from a date object using the date
pipe with specific format strings:
- Year:
'yyyy'
or'y'
- Time:
'mediumTime'
,'shortTime'
, etc.
Example:
<p>{{ today | date:'yyyy' }}</p> <!-- Outputs: 2010 -->
<p>{{ today | date:'mediumTime' }}</p> <!-- Outputs: 12:05:08 PM -->
8. Is it possible to chain multiple Angular pipes together in one expression?
Answer: Yes, you can chain multiple Angular pipes together in a single expression. Pipes are applied from left to right, and the output of each pipe is passed as input to the next.
Example:
<p>{{ today | date:'yyyy' | json }}</p> <!-- Outputs: "2010" -->
9. How can you handle undefined or null values in Angular pipes?
Answer:
When dealing with potentially undefined or null values, it's a good practice to use the safe navigation operator ?.
to prevent errors. Pipes won't throw an error if the input is null or undefined, but the safe navigation operator ensures that the pipe doesn't execute if the input is null or undefined.
Example:
<p>{{ user?.birthdate | date:'medium' }}</p>
<!-- If user.birthdate is undefined or null, nothing will be displayed -->
10. What is the difference between using currency
pipe in an application with default locale and changing the locale explicitly?
Answer:
Using the currency
pipe without explicitly setting the locale will use the application's default locale, which is typically 'en-US'. Changing the locale explicitly allows you to format the currency according to the rules of a specific region, including different symbols, placements, thousands separators, etc.
Example:
Login to post a comment.