app.DeptService.ts

Updated : Oct 26, 2019 in Angular

pipes in angular 4 examples

In this article, we will learn about pipes in angular 4 examples like What are pipes, Parameterized pipes, Custom pipes, Pure and impure pipes, Async pipes

What are the pipes in angular?

In Angular 1.X we used filters to modify (or) format (or) to choose the value within the template. From

Angular >=2.X it is modernized as pipes

  • Pipes are used to transforming the data
  • We can convert the value of one type to another type
  • We can use them as a function
  • Pipes makes your code clean and more structured and can execute functions within templates in an effective way

Syntax:

With a single pipes in Angular

syn: Value | pipe1

Multiple pipes in Angular

syn: Value | pipe1 | pipe2 | pipe3 ……..

Parameterized Pipes

syn: Value | pipe1: param1: param2 | pipe2:param1:param2

Here are a few Built-in pipes in Angular Examples.

  1. DatePipe: Formats a date according to locale rules
  2. UpperCasePipe: Transforms string to uppercase
  3. LowerCasePipe: Transforms string to lowercase
  4. DecimalPiple: Formats a number according to locale rules.
  5. CurrencyPipe: Formats a number as currency using locale rules.
  6. PercentPipe: Formats a number as percentage.
  7. JsonPipe: Converts value into a string using JSON.stringify. Useful for debugging.
  8. SlicePipe: Creates a new List or String containing a subset (slice) of the elements

Let us see examples for the built-in pipes of angular one by one with examples

DatePipe in Angular

Syn: Value | date: format

Here are the few predefined formats for Date pipe

  • ‘medium’: equivalent to ‘yMMMdjms’ (e.g. Sep 3, 2010, 12:05:08 PM for en-US)
  • ‘short’: equivalent to ‘yMdjm’ (e.g. 9/3/2010, 12:05 PM for en-US)
  • ‘fullDate’: equivalent to ‘yMMMMEEEEd’ (e.g. Friday, September 3, 2010 for en-US)
  • ‘longDate’: equivalent to ‘yMMMMd’ (e.g. September 3, 2010 for en-US)
  • ‘mediumDate’: equivalent to ‘yMMMd’ (e.g. Sep 3, 2010 for en-US)
  • ‘shortDate’: equivalent to ‘yMd’ (e.g. 9/3/2010 for en-US)
  • ‘mediumTime’: equivalent to ‘jms’ (e.g. 12:05:08 PM for en-US)
  • ‘shortTime’: equivalent to ‘jm’ (e.g. 12:05 PM for en-US)

File: app.component.ts

Create a component, create a variable of type Date

import { Component} from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: './template.html'
})
export class AppComponent {
    today = new Date();
}

File: template.html

<h3>date pipe </h3>
<p>No pipe: {{today}}</p>
<p>No Format: {{today | date}}</p>
<p>Format – “dd/MM/yyyy” {{today | date:"dd/MM/yyyy"}}</p>
<p>Medium formatted Date: {{today| date:"medium"}}</p>
<p>Short Date: {{today| date:"short"}}</p>
<p>Full Date: {{today| date:"fullDate"}}</p>
<p>Long date: {{today| date:"longDate"}}</p>
<p>Medium formatted date: {{today| date:"mediumDate"}}</p>
<p>Short date: {{today| date:"shortDate"}}</p>
<p>Medium time: {{today| date:"mediumTime"}}</p>
<p>Short time: {{today| date:"shortTime"}}</p>

Decimal Pipe in Angular

Syn: Value | number: digitInfo

digitInfo: It’s a string with the following format

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

  1. minIntegerDigits is the minimum number of integer digits to use. Defaults to 1.
  2. minFractionDigits is the minimum number of digits after fraction. Defaults to 0.
  3. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.

Create a File: app.component.ts

export class AppComponent {
    num = 12.12345;
}

File: template.ts

<p>No Format: {{num}}</p>
<p>Format with 3 digits after decimal (.3-3): {{num | number:'.3-3'}}</p>
<p>Format with 5 digits after decimal (.5-5): {{num | number:'.5-5'}}</p>
<p>Format with 3 digits before decimal and 10 digits after decimal (3.10-10): {{num | number:'3.10-10'}}</p>

Currency Pipe in Angular

syn: Value | currency: currencyCode: symbolDisplay: digitInfo

• currency code is the ISO 4217 currency code, such as USD for the US dollar and EUR for the euro.
• symbol display is a boolean indicating whether to use the currency symbol or code.
1. true: use symbol (e.g. $).
2. false(default): use code (e.g. USD).
• digitInfo is a string as explained in Decimal Filter

Eg: {{emp.salary | currency:'USD':true:'4.2-3'}}

Percentage Pipe in Angular

It converts the number in percentage and also adds the percentage symbol (%) after it.

syn: Value | percent: digitInfo

<p>Formated : {{num | percent}}</p>
<p>Formated (3.2-2) : {{num | percent:'3.2-2'}}</p>

Upper and lower case Pipes in Angular

These two pipes doesn’t accept any parameters and the name of the pipe describes its purpose.

Uppercase pipe

Syn: Value | uppercase

Lowercase pipe

syn: Value | lowercase

<p>UpperCase: {{"Hello World" | uppercase}}</p>
<p>LowerCase: {{"Hello World" | lowercase}}</p>

Json Pipe in Angular

Normally we can display the object properties in the view but not the entire object, so to display the entire object Json pipe is used.

syn: Value | json

Create file File: app.component.ts

export class AppComponent {
    employees: Object = [{ EmpName: "Ramesh", EmpSalary: 10000 }, { EmpName: "Suresh", EmpSalary: 11000 }];
}

File: template.html

<h3> Json pipe</h3>
<p>{{employees | json}}</p>

Slice Pipe in Angular

This slice works similar to the javascript slicing i.e., Array.prototype.slice()

syn: Value | slice: start: end

File: app.component.ts

export class AppComponent {
    employees = [{ EmpName: "Ramesh", EmpSalary: 10000 }, { EmpName: "Suresh",     EmpSalary: 11000 }];
    names = ["Ramesh","Suresh","Lokesh","Durgesh"];
}

File: template.html

<h3>Slice with string</h3>
<p>{{"Hello World" | slice :0:5}} {{"Hello World" | slice :6:11}}</p>

<h3>slice with array and object</h3>
<ul>
    <li *ngFor="let item of names|slice: 0:1">
        <span>{{item}}</span>
    </li>

    <li *ngFor="let item of employees|slice: 0:1">
        <span>{{item |json}}</span>
    </li>
</ul>

Async Pipe in Angular

  • Async pipes unwraps value from an asynchronous primitive or non-primitive. If we have Observable or Promise instance then we can use Async pipe directly with directives like *ngIF, *ngFor, ngSwitch.
  • Async pipes subscribes to Observable or Promise and return the latest data.
  • When a new value is emitted the Async pipe marks the component to be checked for changes and when the component is destroyed the Async pipe automatically gets unsubscribed to avoid memory leaks.

Let us create a component

@Component({
    selector: 'async-pipe',
    templateUrl: './template.html'
})
export class AsyncPipe {
    firstPromise: Promise<string> = null;
    isResolve: boolean = false;
    resolve(): any {
        if (this.isResolve) {
            this.isResolve = false;
            this.firstPromise = new Promise<string>((resolve, reject) => {
                resolve;
            });
        }
        else {
            this.isResolve = true;
            this.firstPromise = new Promise<string>((resolve, reject) => {
                resolve("resolved");
            });
        }
    }
}

File: template.html

<h3>Async Pipe using promise</h3>
<p>{{firstPromise | async}}</p>
<button (click)="resolve()"> {{isResolve ? 'Reset' :'Resolve'}}</button>

Async pipe with *ngIF *ngFor and ngSwitch

Using *ngIF

export class AsyncPipe {
emp = { EmpId: 1, EmpName: "Ramesh", EmpSalary: 10000 };
    employee: Promise<Object> = new Promise<Object>((resolve, reject) => {
        resolve(this.emp);
    });
}

File: template.html

<p *ngIf="employee |async as emp;else loading">{{emp.EmpId}}. {{emp.EmpName}}</p>
<ng-template #loading>Loading...</ng-template>

Using *ngFor

export class AsyncPipe {
lstEmployees = [{ EmpId:1,EmpName: "Ramesh", EmpSalary: 10000 }, { EmpId:2,EmpName: "Suresh", EmpSalary: 11000 }];
    employees: Promise<Object> = new Promise<Object>((resolve, reject) => {
        resolve(this.lstEmployees);
    });
}

File: template.html

<ul>
    <li *ngFor="let emp of employees|async ">
        {{emp.EmpId}}. {{emp.EmpName}}
    </li>
</ul>

Using ngSwitch

<div  [ngSwitch]="(employee|async)?.EmpId">
    <div *ngSwitchCase="1">{{emp.EmpName}}</div>
    <div *ngSwitchDefault>Hello world !</div>
</div>

? the above article we are discussed with builtin pipes in angular 4 examples next article we will see how to implement the custom pipes in angular

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *