An Introduction to Angular Pipes

Angular is recognized among the dominating frontend frameworks used for UI development especially because of its features and great performance delivery. In this article, we will shed light on one of the essential topics of Angular i.e., Angular pipe.

What is Angular Pipe?

Angular pipes are used to filter the data and it is denoted by the | symbol. It holds the string, integers, arrays, and date as input separated with |. It transforms the data in the format as needs and displays the same in the browser. It takes data as input and converts it to the desired output. Pipes are very useful because we can use it in the entire application, while only declaring each pipe once. For example, you would use a pipe to show the date as September 15, 1997, instead of the raw string format.

Built-in Pipes

Angular Offers built-in pipes for particular data transformation, including transformation for internationalization (i18n), which use locale info for that data. The following are generally used built-in pipes for data transformation.

  • AsyncPipe: Disclose a value from an asynchronous primitive.
  • DatePipe: Transform a date value according to locale rules
  • UpperCasePipe: Convert the text data into the upper case.
  • LowerCasePipe: Transform the text data into a lower case.
  • CurrencyPipe: Transfigure the number to a currency string, Arranged in the format according to locale rules.
  • DecimalPipe: Transform the number into a string with a decimal point, Arranged in the format according to locale rules.
  • PercentagePipe: Transform the number to a percentage string, Arranged in the format according to locale rules.
  • JsonPipe: Transform a value into its JSON (JavaScript Object Notation) format representation. It is useful for debugging.
  • SlicePipe: Creates a new Array or String having a subset(slice) of the elements.
  • TitleCasePipe: Transform the text to title case. Capitalizes the first letter of each word and transforms the other word to lower case. Words are delimited by any whitespace character, like space, tab, or line-feed character.

 ☞ Start Your Online Learning From Udemy With Amazing Student Discount & Offers

To understand the functional capability of these built-in pipes, in your app open app.component.ts file and change the file code as per following code:

// This method transmits the string value passed as a parameter to the component’s method after three seconds have passed, using the of and delay methods.

  makeObservable(value: string): Observable<string> {

    return of(value).pipe(delay(3000));

  }

  title = angularPipesDemo‘;

  dateOfToday = new Date();

  userData = { userName: Jignesh‘, userAge: 32‘, userAddress: { city: Mumbai‘, state: Maharashtra } };

  monthName = [Jan‘, Feb‘, Mar‘, April‘, May‘, Jun‘, July‘, Sept‘, Oct‘, Nov‘, Dec];

}

To pass these pipes open app.component.html file and change the file code as per the following code:

See also  Node.js vs PHP : Which one is Better For Backend Development?

<!– This Pipe will convert the data in Upper Case –>

<h4>Title In Uppercase using uppercase pipe</h4>

<p>{{title | uppercase}}</p>

<!– This Pipe will convert the data in Lower Case –>

<h4>Title In Lowercase using lowercase pipe</h4>

<p>{{title | lowercase}}</p>

<!– This Pipe will convert the data in title Case –>

<h4>Title In Title Case using titlecase pipe</h4>

<p>{{title | titlecase}}</p>

<!– This Pipe will convert the data in the required currency –>

<h4>Currency Pipe using Currency Pipe</h4>

<p>{{5678.90 | currency:”INR”}}</p>

<p>{{5678.90 | currency:”USD”}}</p>

<!– This Pipe will transform the data in to required dat format –>

<h4>Date of Today using Date pipe</h4>

<p>{{dateOfToday | date:’d/M/y’}}</p>

<p>{{dateOfToday | date:’shortTime’}}</p>

<!– This Pipe will transform the data to the decinal format–>

<h4>User Salary in decimal using Decimal Pipe</h4>

<!–4 is for main integer, 3 -4 are for integers to be displayed.–>

<p>{{ 565.8787876 | number: ‘4.3-4’ }}</p>

<!–This Pipe will transform the data to JSON format –>

<h4>User Data in Json format using Json Pipe</h4>

<p>{{ userData | json }}</p>

<!– This Pipe will convert to the percentage –>

<h4>User attendence in Percent using Percent Pipe</h4>

<p>{{00.78789 | percent}}</p>

<!– This Pipe will slice the array Data –>

<h4>Slice the Array data using Slice Pipe</h4>

<!– 0 & 11 refers here to the start and end index –>

<p>{{monthName | slice:0:9}}</p>

<!– This async pipe will call the then method of the promise and it will subscribe and unsubscribe from the observable routinely. –>

<p>

    {{asyncPromise | async}}

</p>

<p>

    {{asyncObservable | async}}

</p>

Below mentioned output is the output of the above code after running the AngularPipeDemo app.

See also  Competitive Programming – A Complete Guide

 

Following Async Pipe Output will generate after 3 seconds :

How to create Custom Pipe in Angular?

We can create a custom pipe in angular using the following code:

ng generate pipe <nameOfPipe>

or

ng g p <nameOfPipe>

If you want to create the pipe named with SquareRootPipe then run the following command:

ng generate pipe squareRoot

Or

ng g p squareRoot

After executing the following command the files will generate

  • square-root.pipe.ts:- This file is used for custom logic for pipe/filter the data
  • square-root.pipe.spec.ts:- This file used for testing purpose

In addition to this app.module.ts also get updated. The following code snippet file is the app.module.ts file

import { BrowserModule } from @angular/platform-browser‘;

import { NgModule } from @angular/core‘;

import { AppRoutingModule } from ./app-routing.module‘;

import { AppComponent } from ./app.component‘;

import { SquareRootPipe } from ./square-root.pipe‘;

@NgModule({

  declarations: [

    AppComponent,

    SquareRootPipe

  ],

  imports: [

    BrowserModule,

    AppRoutingModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Go to square-root.ts file:

You can see the SquareRootPipe is implemented from PipeTransform

What is Pipe Transform?

An interface that is implemented by pipes for the person of performing a transformation. Angular invokes the transform method with the data value of a binding as the initial argument and any parameters as the second argument in the form of list.

Call transform using the value of type number and using this value perform the sqrt Math function.

The following code is a code snippet of square-root.pipe.ts file

import { Pipe, PipeTransform } from @angular/core‘;

@Pipe({

  name: squareRoot

})

export class SquareRootPipe implements PipeTransform {

  transform(value: number): number {

    return Math.sqrt(value);

  }

}

Now use this pipe to the component, following is the code snippet of app.component.html file

<div>

    <h2> Demo Of Custom Pipes </h2>

</div>

<h3> Squre root of 36 is : {{ 36 | squareRoot }} </h3>

<h3> Squre root of 50 is : {{ 50 | squareRoot }} </h3>

Here is the output of the beyond code snippet:

 Conclusion

In this blog, we have seen Angular pipes which are Angular built-in Pipes and Angular custom Pipes. In built-in pipes, we have seen the types of different built-in pipes with syntax and example of it. Then in custom pipes, we have seen the step to generate custom pipe required files by writing the commands and by modifying the changes for custom pipe logic and used in component Html file.

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd. Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and have been associated with AngularJS Frontend development companies.
Vinod SataparaVinod Satapara

Digital Web Services

Digital Web Services (DWS) is a leading IT company specializing in Software Development, Web Application Development, Website Designing, and Digital Marketing. Here are providing all kinds of services and solutions for the digital transformation of any business and website.

We will be happy to hear your thoughts

      Leave a reply

      Digital Web Services
      Logo