Angular tutorial : How to Create Custom Pipe in Angular

Angular tutorial : How to Create Custom Pipe in Angular

Pipes in Angular are a great way to transform and format data right from your templates. Out of the box you get pipes for dates, currency, percentage and character cases, but you can also easily define custom pipes of your own.This is where the concept of creating a Custom Pipe in Angular comes into play, allowing us to nicely extend our applications.

Pipes in Angular are a great way to transform and format data right from your templates. Out of the box you get pipes for dates, currency, percentage and character cases, but you can also easily define custom pipes of your own.This is where the concept of creating a Custom Pipe in Angular comes into play, allowing us to nicely extend our applications.

What are pipes in Angular?

Angular provides some helpful filters known as Pipes which makes it very easy to format or transform the data value according to our needs.
Pipes are used with a Pipe (|) character, it takes an input and returns a desired formatted output. Simple Right?

Angular has a few built-in Pipes that ship with the framework’s CommonModule, allowing us to make use of them in any module we’re writing.

Here are a few usual suspects we could encounter with Angular’s built-in Pipes:

  • DatePipe (for parsing Date objects)
  • UpperCasePipe (for uppercase-ing Strings)
  • LowerCasePipe (for lowercase-ing Strings)
  • CurrencyPipe (for formatting currencies)
  • AsyncPipe (for unwrapping asynchronous values, such as Observables!)

In simple terms, pipes allow us to write display value transformation right inside the template. Angular comes with stock or built in pipes to transform your values to what you want the user to see. For instance, the Date Pipe, allows you to change the date format and other aspects related to the date.

That’s the essence of a Pipe!

So, how do we use a Pipe? Let’s assume some simple component HTML with a binding of a Date stamp:

<div>
  <!-- Renders: 21/10/2019 -->
  <p></p>
</div>

This could render out as above with the formatted Date. So that’s a valid use case for Pipes! We don’t really want to fetch data and then loop through it all and convert each date from a Date object to a String, as we’d lose native Date object functionality and be duplicating values. It’s super convenient to use a Pipe and let it parse out for us!

Now you’re ready to start venturing into Custom Pipes! This will allow us to use a function to create our own input and output based on what you’re supplying. Let’s dive in!

Using Custom Pipes

Let’s assume an image was just uploaded via a drag and drop zone - and we’re getting some of the information from it. A simplified file object we’ll work with:


export class FileComponent {
  file = { name: 'logo.svg', size: 2120109, type: 'image/svg' };
}


Properties name and type aren’t what we’re really interested in to learn about Pipes - however size is the one we’d like. Let’s put a quick example together for how we’ll define the usage of our pipe (which will convert numbers into filesizes):


<div>
  <p></p>
  <p></p>
</div>

Creating a Custom Pipe

To create a Pipe definition, we need to first create a class (which would live in its own file). We’ll call this our FileSizePipe, as we are essentially transforming a numeric value into a string value that’s more human readable:

export class FileSizePipe {}


Now we’ve got this setup, we need to name our Pipe. In the above HTML, we did this:


<p></p>

So, we need to name the pipe “filesize”.

import { Pipe } from '@angular/core';

@Pipe({ name: 'filesize' })
export class FileSizePipe {}

All we need to do is supply a name property that corresponds to our template code name as well (as you’d imagine).

Don’t forget to register the Pipe in your @NgModule as well, under declarations:

// ...
import { FileSizePipe } from './filesize.pipe';

@NgModule({
  declarations: [
    //...
    FileSizePipe,
  ],
})
export class AppModule {}

NOTE : Pipes tend to act as more “utility” classes, so it’s likely you’ll want to register a Pipe inside a shared module. If you want to use your custom Pipe elsewhere, simply use exports: [YourPipe] on the @NgModule.

Pipe and PipeTransform

Once we’ve got our class setup, registered, and the @Pipe decorator added - the next step is implementing the PipeTransform interface:

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

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
  transform() {}
}

This creates a required contract that our FileSizePipe must adhere to the following structure:

export interface PipeTransform {
  transform(value: any, ...args: any[]): any;
}

Which is why we added the transform() {} method to our class above.

Pipe Transform Value

As we’re using our Pipe via interpolation, this is the magic on how we’re given arguments in a Pipe.

The file.size variable is passed straight through to our transform method, as the first argument.

We can call this our size and type it appropriately:

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number) {}
}

From here, we can implement the logic to convert the numeric value into a more readable format of megabytes.

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number): string {
    return (size / (1024 * 1024)).toFixed(2) + 'MB';
  }
}


We’re returning a type string as we’re appending 'MB' on the end. This will then give us:

<!-- 2.02MB -->

We can now demonstrate how to add your own custom arguments to custom Pipes.

Pipes with Arguments

So let’s assume that, for our use case, we want to allow us to specify the extension slightly differently than advertised.

Before we hit up the template, let’s just add the capability for an extension:

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB'): string {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

I’ve used a default parameter value instead of appending the 'MB' to the end of the string. This allows us to use the default 'MB', or override it when we use it. Which takes us to completing our next objective of passing an argument into our Pipe:

<!-- 2.02megabyte -->


And that’s all you need to supply an argument to your custom Pipe. Multiple arguments are simply separated by :, for example:

Don’t forget you can chain these pipes alongside others, like you would with dates and so forth.

Here’s the final assembled code:


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

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB') {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

Want a challenge? Extend this custom Pipe that allows you to represent the Pipe in Gigabyte, Megabyte, and any other formats you might find useful. It’s always a good exercise to learn from a starting point!

Learn More

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Best 17 Angular Libraries Every Angular Developers Should Know in 2019

Best 17 Angular Libraries Every Angular Developers Should Know in 2019

In this article, we list 17 useful Angular libraries that can help as you develop applications with Angular.

Angular is a web development framework for building robust single-page applications and systems. Developed and maintained by Google and community maintainers, Angular is a great library for building large scale web applications.

Angular has a huge and active community, thus, a lot of libraries have been introduced by the community to plug holes and extend the tooling provided by Angular. Today, we’ll look at some libraries that can be introduced into existing applications — libraries ranging from utility libraries to UI component libraries.

1. ng-bootstrap

It seems fair to start with the Angular implementation of the most popular UI library. The ng-bootstrap library was built from the top down using TypeScript. Unlike the previous version, it has dropped jQuery as a dependency, specifying Bootstrap’s CSS as its only other dependency. With most JavaScript components implemented, the library seems like a complete solution when using Bootstrap with Angular — as active development is ongoing, more components will be included. With almost 7k stars on GitHub, ng-bootstrap seems like a very popular choice for a lot of Angular developers.

The Angular.js version of this project is still available here, although it isn’t actively maintained.

2. Angular Google Maps

Using the Google Maps library in Angular is always a serious hassle because the library is loaded using a script tag, so type definitions aren’t readily available. This causes some compile errors that need a lot of hacking to get rid of.

The Angular Google Maps library provides services and directives for implementing Google Maps services. There are directives available for creating maps, using markers, etc. The library also provides an async function that is useful for checking if the Google Maps library is loaded on the webpage.

The project has amassed almost 2k stars on GitHub. Visit their documentation to get started.

3. ngx-translate

Building an application that supports multiple languages can be a serious struggle, especially for single-page applications. The ngx-translate is a great library for managing multiple languages in your Angular application. It provides services to load translations that can be used throughout the application. Translations can be defined and loaded using the TranslateService, and onChange listeners are also available for handling language changes within the application.

The setup is pretty straightforward, and the library is well documented with detailed examples. Visit their GitHub page to get started.

4. Angular2-jwt

Managing single-page applications that use web tokens for authentication usually requires using interceptors to append headers to network requests. While this is easy to implement, it is difficult to filter out requests that don’t require access tokens. This is where this impressive library comes in. Using the angular-jwt package by Auth0, you can load access tokens from the local storage or session storage. It provides an HttpInterceptor that appends authentication headers to the requests. The ability to blacklist or whitelist a domain is also available.

With almost 2k stars on GitHub, it is a well-documented library with adequate examples and only requires a few steps to get started.

5. AngularFire2

Looking to implement real-time functionality in your Angular application? Well look no further, this library uses the power of RxJS, Firebase and Angular to deliver data synchronization in real time. It also provides services and providers to query documents and collections on Cloud Firebase and the realtime database, handles authentication using Firebase, handles file upload to Cloud Storage, and sends Push Notifications. The package also supports server-side rendering and offline functionality. You can easily import each individual module to handle whichever functionality is required in your application. All documentation can be found in the library’s GitHub page.

6. ng2-file-upload

Handling file uploads in any single-page application isn’t a task that’s fun to deal with. It would be great if an external library could handle file upload within your web application. Valon-software, the makers of ngx-bootstrap, has you covered with ng2-file-upload, a library that makes file upload a breeze.

The library supports drag-and-drop functionality alongside the good old file select implementation. It provides a utility class (FileUploader) that handles the different file upload methods. It also provides events to monitor the file upload progress, as well as errors and success during the upload.

The library is actively maintained and has almost 2k stars on Github.

7. Angular Material 2

The list wouldn’t be complete without mentioning a library that implements Google’s Material Design specifications. Angular Material 2 is a components library created by the Angular team. It features a set of components implementing the Material Design specs, ranging from buttons to dialogs, bottom sheets, etc. It features fully customizable themes and a rich set of components that can be used to quickly build an application. Angular Material 2 comes with almost 40 components, with more components under development and four pre-built themes.

Get started with Angular Material 2 by visiting their documentation or GitHub page.

8. ngrx/store

Managing state in small applications isn’t really complicated and state can be easily managed within individual components, but when there’s a need to share data between several components, the need for a proper state management system arises. NgRx offers reactive libraries optimized for Angular. It offers reactive statement for Angular in a package called ngrx/store. This package uses RxJS technologies to offer state management similar to Redux. The store allows developers write consistent and performant applications in a state-controlled environment. Very similar to Redux, the ngrx/store library uses Action, Reducers, Select and Store to manage the data flow within Angular applications. Get started with ngrx/store by following the steps listed in the library’s documentation.

9. Cloudinary Angular SDK

Cloudinary is SaaS web platform for managing media assets on mobile and web applications. It provides services for upload, storage, manipulation and delivery of media assets. Cloudinary offers an SDK for Angular that can be used in Angular applications for resizing and image conversion. The SDK can also be used for delivering different image sizes on different screens. It allows for easy delivery of video and image assets from Cloudinary’s storage.

Visit Cloudinary’s website to read more about about end-to-end management of media assets. The SDK can be found here on GitHub.

10. ng2-pdf-viewer

The ng2-pdf-viewer is a library for viewing and interacting with PDFs on a web application. The library providers a component for rendering PDF documents. The component can also be used for performing operations on the selected PDF like: resizing, rotating, searching through the document, etc. You can render files locally or provide a link to an external document. This library is great for managing PDF files on your web application, and there’s a lot it can handle using directives.

Visit their official documentation page or their page on GitHub.

11. ngx-charts

When working with data in a web application, the need for data visualization arises, thus the need for a data visualization library that can handle various forms of customizations while rendering. ngx-charts is quite interesting because their charts rely mostly on using Angular to animate SVGs, which offers more speed and flexibility as the library has been optimized for use in Angular.

It also uses d3 for math functions, scales and axis, etc. It comes with ten or more color schemes while making the charts fully customizable using CSS. Visit their demo page to view the different themes and color schemes available and their GitHub page to get started with the library. The library has garnered almost 3k stars on GitHub and is actively maintained.

12. ng-seed/universal

This great library has so many features packaged within it, it should be the Swiss army knife for every Angular developer. It consists of the following packages:

  • ngx-meta: for handling meta tags, title tags and SEO enhancement.
  • ngx-cache: for managing application wide data.
  • ngx-auth: for managing jwt-based authentication.

It comes with a couple of other packages for handling server-side rendering, lazy loading, state management and webpack configurations.

Clone the repository on GitHub and follow the instructions to get started.

13. Augury

When building web applications, browser DevTools play an important part in the development process. It provides features for debugging, diagnosing and editing web applications. When dealing with Angular applications, DevTools only lets you interact with the end product of your code, which means your Angular components, directives, etc. have been converted to JavaScript, HTML and CSS.

Augury as a browser extension allows you debug and visualize your Angular application in its pre-compiled state. With Augury, you can inspect your components and ensure they’re functioning as they should. Augury works better with source maps, so ensure that you generate source maps for a better experience while using Augury.

You can download the extension for Chrome or Firefox. Visit their GitHub page if you wish to contribute or raise issues.

14. ngx-moment

Moment.js is a utility library for manipulating time (not what you think). It provides a set of functions for parsing, formatting, validating, etc. dates and time using JavaScript. ngx-moment builds on the Moment.js library, providing Angular pipes for use within components. It comes packed with pipes for the functions provided by Moment.js, thus effectively eliminating the overhead of importing the functions into every component for use.

The library is actively maintained and is relatively easy to get started with. Visit the GitHub page and run through the documentation to get started.

15. ngx pipes

Fun times when Angular.js came packed with a set of pipes for transforming data before rendering. Filters is what they were called in Angular.js. Well, for some performance reasons, more recent Angular versions don't include pipes for filtering or ordering lists. Angular pipes is a library that contains a set of useful pipes for use in your Angular project. It contains pipes for performing actions like: trimming, reversing, matching and scanning strings, plucking, shuffling and ordering Arrays.

It is well documented and easy to integrate. Getting started should be a breeze and, soon enough, you’ll start getting more done with pipes. Visit the documentation or their GitHub page to get started.

16. Angular Epic Spinners

When dealing with interactivity on a webpage, you have to think about notifying users when processes not visible to them are ongoing. When the time comes, you are required to display a loading indicator. Some sites have custom loading indicators for their application, but if you’d rather have a set of easily available spinners, then this spinners library should be your go-to.

Angular Epic Spinners is built on the epic-spinners library, with Angular components for each component available in the library. Each component can be imported as an individual module and rendered anywhere within your application. You can select from any of 20 indicators available in the library. You can view the demo page or head straight to their GitHub page.

17. Apollo Angular

GraphQL is a query language for APIs and a runtime for fulfilling queries made with data. It allows developers to request for data they need in specific areas of their application. Apollo client is a library used to consume data from GraphQL endpoints. Apollo has different client libraries for consuming data on the frontend – libraries exist for React, Angular, Vue, etc.

Apollo Angular is a client library built for Angular applications to consume GraphQL endpoints. Apollo Angular is agnostic of any router used within the application. It also supports server-side rendering. The documentation page is well written with adequate examples to help you get started.

Summary

People sometimes avoid using external libraries in their applications during development. While that’s acceptable in some instances, external libraries can help reduce development time significantly. There are a lot of libraries that might have achieved whatever you’re struggling with during development. The task is finding the right library that fits into your applications and ensuring it fulfills its purpose. Happy coding.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Web Developer Bootcamp

Angular 8 is coming

MEAN Stack Angular 8 CRUD Web Application

Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

Top Node.js Development Companies and Expert NodeJS Developers

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world.
List of Leading Node.js development Service Providers & Developers...