ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Working with Angular Pipes

Angular Pipes takes data as input and formats or transform the data to display in the template. We use them to change the appearance of the data before presenting it to the user. The most common use case of pipes is displaying the dates in the correct format as per the user’s locale.

In this tutorial, we will show you how to use Angular Pipes. We will see how to pass arguments to the pipe and how to chain multiple pipes. We are also going to look at the few of the angular built-in pipes like currency pipe, date pipe, number pipe,percent pipe ,decimal pipe, & slice pipe etc.

Angular Pipes Syntax

The syntax of the pipe is as follows

                              
 
Expression | pipeOperator[:pipeArguments]
                            
                        

Where

Expression : is the expression, which you want to transform
| : is the Pipe Character
pipeOperator : name of the Pipe
pipeArguments : arguments to the Pipe

Pipes Example

In this example let use Angular built in date pipe to transform the date

Component class

                              

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    templateUrl: `<p> Unformatted date : {{toDate }} </p>
                  <p> Formatted date : {{toDate | date}} </p>` 
}) 
export class AppComponent 
{ 
    title: string = 'pipe Example' ; 
    toDate: Date = new Date(); 
}
                            
                        

In the above example, we are taking current date and transforming it into the easily readable format using the date pipe. We have included the unformatted date format for comparison. The output is as shown below

image

Example of Angular Pipes

Passing arguments to pipes

We can also pass optional arguments to the pipe. The arguments are added to the pipe using a colon (:) sign followed by the value of the argument. If there are multiple arguments separate each of them with the colon (:). For example, we can pass the format as the argument to the date pipe, which is Optional. The medium is one of the valid value of the format argument, which displays the date in yMMMdjms format. The example code is as shown below.

                              

{{toDate | date:'medium'}}
                            
                        

The parameter medium displays the date as Nov 22,2016, 10:04:10 PM

Chaining Pipes

Pipes can be chained together to make use of multiple pipes in one expression. For example in the following code, the toDate is passed to the Date Pipe. The output of the Date pipe is then passed to the uppercase pipe.

                              

{{toDate | date:'medium'}}
                            
                        

The Angular Built-in pipes

The Angular has several built-in pipes, which you can use in your application. You can read about them from thislink

Some of the important pipes are Date Pipe, Uppercase Pipe,Lowercase Pipe,Number Pipe/ Decimal Pipe,Currency Pipe, and Percent Pipe, etc

DatePipe

The Date pipe formats the date according to locale rules. The syntax of the date pipe is as shown below

                              

{{toDate | date:'medium'}}
                            
                        

Where

date_expression is a date object or a number

date is the name of the pipe

format format is the date and time format string which indicates the format in which date/time components are displayed.

Some of the common format strings are

Component format Example
Year y 2016
Year yy 16
Month M 9
Month M 99
Month MMM Nov
Month MMMM November
Day d 9
Day dd 09
hour j 9
hour jj 09
hour h 9 AM
hour hh 09 AM
hour24 H 13
hour24 HH 13
minute m 9
minute mm 09
second s 9
second ss 99
second ss 99
Time zone z Pacific Standard time
Time zone Z GMT-8:00
Time zone a PM
era G AD
era GGGG Anno Domini
Format Name Equivalent Format strng Example(for en-US)
medium yMMMdjms Sep 3, 2010, 12:05:08 PM
short yMdjm 9/3/2010, 12:05 PM
fullDate yMMMMEEEEd Friday, September 3, 2010
longDate yMMMMd September 3, 2010
mediumDate yMMMd Sep 3, 2010
shortDate yMd 9/3/2010
mediumTime jms 12:05:08 PM
shortTime jm 12:05 PM

Format argument also supports some predefined commonly used formats

You can read about the complete list from link

Example of Datepipe

                              
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template:`<p>medium : {{toDate | date:'medium'}} </p>
              <p>short : {{toDate | date:'short'}} </p>
              <p>fullDate : {{toDate | date:'fullDate'}} </p>
              <p>longDate : {{toDate | date:'longDate'}} </p>
              <p>mediumDate : {{toDate | date:'mediumDate'}} </p>
              <p>shortDate : {{toDate | date:'shortDate'}} </p>
              <p>mediumTime : {{toDate | date:'mediumTime'}} </p>
              <p>dd-MM-y : {{toDate | date:'dd-MM-y'}} </p>
              <p>dd-MM-yy HH:mm : {{toDate | date:'dd-MM-yy HH:mm'}} </p>`
})
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    toDate: Date = new Date();
}
 
                            
                        

UpperCasePipe & LowerCasePipe

As the name suggests, these pipes transform the string to Uppercase or lowercase

                              

 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    template:`<p>Unformatted :{{msg}} </p>
              <p>Uppercase :{{msg | uppercase}} </p>
              <p>Lowercase :{{msg | lowercase}} </p>`
})
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    msg: string= 'Welcome to Angular';
}
 
                            
                        

Read more about uppercasepipe & lowercasepipe

SlicePipe

Creates a new List or String containing a subset (slice) of the string or array. This Pipe uses the JavaScript API Array.prototype.slice() and String.prototype.slice().

Syntax

                              

 
array_or_string_expression | slice:start[:end]
 
                            
                        

Where

array_or_string_expression is the string to slice

slice is the name of the pipe

start is the start position/index from where the slicing will start

end is the ending index/position in the array/string

The slice pipes take two arguments. The first argument start is the starting index of the string/array. The second argument end is the ending index of the string/array. If the start or end index is negative then the index is counted from end of the string/array

Example

                              

 

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template:`<p>Complete String :{{msg}} </p>
              <p>Example 1 :{{msg | slice:11:20}} </p>
              <p>Example 2 :{{msg | slice:-9}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    msg: string= 'Welcome to Angular ';
}
 
Both the above examples will d
 
                            
                        

Both the above examples will display Angular. You can read more about slice from this link

DecimalPipe / NumberPipe

The Decimal Pipe is used to Format a number as Text. This pipe will format the number according to locale rules.

Syntax

                              

number_expression | number[:digitInfo]
                            
                        

Where

number_expression is the number you want to format

number is the name of the pipe

digitInfo is a string which has the following format

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Where

minIntegerDigits is the minimum number of integer digits to use. Defaults to 1.

minFractionDigits is the minimum number of digits after fraction. Defaults to 0.

maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.

Example

                              

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template: `<p> Unformatted :{{num}}</p>
               <p> Formatted :{{num | number}}</p>
               <p> Formatted :{{num | number:'3.1-2'}}</p>
               <p> Formatted :{{num | number:'7.1-5'}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    num: number= 9542.14554;
}
                            
                        

PercentePipe

Formats the given number as a percentage according to locale rules.

                              

 
number_expression | percent[:digitInfo]
                            
                        

Where

number_expression is the number you want to format

percent is the name of the pipe

digitInfo is a string which has the following format. It is similar to used in decimal pipe

Example code

                              

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    template:`<p>Unformatted :{{per}} </p>
              <p>Example 1 :{{per | percent }} </p>
              <p>Example 2 :{{per | percent:'1.2-2'}} </p>`
})
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    per: number= .7414;2';
}
                            
                        

More about Percent pipe from the link

CurrencyPipe

Formats a number as currency using locale rules.

                              

 
number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
                            
                        

Where

number_expression currency to format a number as currency.

Currency is the name of the pipe

currencyCode is the ISO 4217 currency code, such as USD for the US dollar and EUR for the euro.

symbolDisplay is a boolean indicating whether to use the currency symbol or code. Use true to display symbol and false to use code

digitInfois similar to the one used in decimal pipe

Example

                              
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template: `<p>Unformatted :{{cur}} </p>
               <p>Example 1 :{{cur | currency }} </p>
               <p>Example 2 :{{cur | currency:'INR':true:'4.2-2'}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular pipes Example' ;
    cur: number= 175;
}
                            
                        

Read more about the currencyPipe from the link