Angular 4 Pipes Tutorial with Examples

Опубликовано: 13 Октябрь 2024
на канале: dotsway
6,456
29

Angular 4 Pipes Tutorial

In this Angular Pipes Tutorial i will showcase built-in pipes like
Angular uppercase pipe
Angular lowercase pipe
Angular date pipe
Angular currency pipe
Angular percent pipe

If you want to know how to Install Angular 4 or check my first Angular 4 Tutorial please check Angular 4 QuickStart - Part 1:
https://goo.gl/pS4eEz

Angular 4 Structure:
https://goo.gl/6J22gr

How to Create a Component in Angular 4 :
https://goo.gl/493WD6

Angular 4 Simple Binding:
https://goo.gl/aaiqxd


Pipes are a way to convert, filter or transform one data to another format. For example you can use a pipe to convert all your strings to uppercase, Earlier in Angular 1.x the same function was there under filter.

Angular 2 and Angular 4 they come with built in pipes, a variety to use without writing any extra code, you can also create your own pipes to use them later in you code.

Using Pipes

Pipes symbols is '|' and it can be use by following the below syntax:

HTML:
My name is {{name | uppercase}}

In above example the name string will be transformed to all uppercase.

Examples for built-in pipes

Uppercase pipe


app.component.html

My daughter name is {{name | uppercase}}

The output will be DANA MELIK although it was defined as 'Dana Melik'. This was done without creating any new function or pipe as it's a built-in pipe which comes with Angular 4.



Lowercase pipe

app.component.html

My daughter name is {{name | lowercase}}

Above example will produce all lowercase.





Currency pipe

app.component.ts

pprice= '234.25' ;

app.component.html

{{pprice | currency: 'USD'}}



Percent pipe

app.component.ts

score = 10/40 ;

app.component.html

{{score | percent }}



Date pipe

Date pipe will output the date in a human readable format.

app.component.ts

tDate = new Date() ; // This will create new date with the current day and time

app.component.html

Below will show only the date without the current time.

Today is: {{tDate | date}}



Date pipe optional parameters

You can pass along with the pipe optional parameters to customize the date output.

Syntax: date : "MM/dd/yy"

This will output the date in Month/Day/Year format.

Today is: {{tDate | date: "MM/dd/yy"}}

Syntax: date : "MM/dd/yy hh:mm"

I added here hh:mm for showing the current time in hours and minutes.

Today is: {{tDate | date: "MM/dd/yy hh:mm"}}

Other examples:

Today is: {{tDate | date: 'shortDate'}}
Today is: {{tDate | date: 'fullDate'}}



Combining and Chaining Pipes

You can also combine several pipes together, having the date in readable format and yet capital can be achieved by using 'date' and 'uppercase'.

Example:

Today is: {{tDate | date | uppercase}}