How to create custom pipes in Angular

How to create custom pipes in Angular

In this article we are going to discuss how to create custom pipes in Angular. If you are new to Angular then please explore our angular series in the link. Let’s first discuss what is a Pipe in angular.

What is a Pipe in Angular ?

Every application runs doing a simple task : get data, transform them, and show them to users. Introducing Angular pipes, a way to write display-value transformations that you can declare in your HTML.

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are used for data transformations in an Angular application.

Built-in Pipes Provided by Angular

  • CurrencyPipe
  • DatePipe
  • DecimalPipe
  • JsonPipe
  • LowerCasePipe
  • UpperCasePipe
  • PercentPipe
  • SlicePipe
  • AsyncPipe etc..

To check all built-in pipes provided by angular please explore our angular series in this link.

Create a Custom Pipe in Angular

We take a example of how a description box have a minimal filed using custom pipes. Let’s say a description text is about 500 characters but you want to show it only 50 chars. and on tool tip you may show all the characters.

Let’s create a Angular 9 application using Visual Studio Code.

  • Open the VS Code
  • Open the VS Code Terminal Window
  • Add the below command to create a new project
Angular NewProject
CoreSpider– Angular New Project with routing Yes and style as css

After creation of the project then move into the project folder using below command.

cd ng-custom-pipe

Create a new component named as “product” using below command

ng g c product
Product Component
Product Component

Open the Product.ts file add the dummy product information like this.

After adding the product component, it automatically add in the module.ts in the root folder.

Product Component in module.ts
Product Component in module.ts

Then remove all the predefined HTML body content in app.component.html.

Component in router outlet
Product Component in router outlet

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  products: any[];
  constructor() {
    this.products = [
      { id: '001', name: 'Laptop', model: 'HP-Pavilion', price: 62000, quantity: 1,
                description: 'HP Pavilion 15 is a Windows 10 laptop with a 15.60-inch display that has a resolution of 1366x768 pixels. It is powered by a Core i7 processor and it comes with 8GB of RAM. The HP Pavilion 15 packs 1TB of HDD storage. Graphics are powered by Nvidia GeForce 940MX'},
      { id: '002', name: 'Mobile', model: 'Samsung-Note10', price: 125000, quantity: 2,
                description: 'Samsung Galaxy Note 10 is powered by a 1.9GHz octa-core Samsung Exynos 9825 processor that features 4 cores clocked at 1.9GHz, 2 cores clocked at 2.4GHz and 2 cores clocked at 2.7GHz. It comes with 8GB of RAM. The Samsung Galaxy Note 10 runs Android 9 Pie and is powered by a 3500mAh battery.'}
    ];
  }

  ngOnInit(): void {
  }

}

<h2>Product Information</h2>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Model</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let prod of products'>
            <td>{{prod.id}}</td>
            <td>{{prod.name}}</td>
            <td>{{prod.model}}</td>
            <td>{{prod.price}}</td>
            <td>{{prod.quantity}}</td>
            <td>{{prod.description}}</td>
        </tr>
        <tr *ngIf="!products || products.length==0">
            <td colspan="7">
                No Products to display
            </td>
        </tr>
    </tbody>
  </table>

Run the application and you can see the output like below; You can see the description is printed here with full text characters.

custom pipes in Angular-datashow
CoreSpider– Product output

How to use Custom Pipes

Let’s introduce with custom pipes and do the description with minimal characters. Let’s create a new folder named as “CustomPipe” and add a angular pipe using below command.

ng g pipe custom-text-length
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customTextLength'
})
export class CustomTextLengthPipe implements PipeTransform {

  transform(value: string, limit?: number) {
    if (!value)
    {
      return null;
    }
    const actuallimit = (limit) ? limit : 75;
    return value.substr(0, actuallimit) + '......';
  }
}

Code Explanation

We create the custom pipe named as customTextLength and here you can see we add the limit text as 75 characters that means when we add this custom pipe into angular interpolation it limit the filed.

custom pipes in Angular-custom pipe dynamic description
https://corespider.com/ – Custom Pipe add

Let’s run the application and see the description field now is limited to 75 characters and on tool tip you can see full text.

custom pipes in Angular-output
CoreSpider– Custom pipe output

Summary

This article explain how to create custom pipes. if have any suggestion then please give your feedback.

That’s a wrap for this article. I hope that it cleared about How to create custom pipes in Angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

Angular 10 with ASP.NET Web API-CRUD Operations
Angular-10-with-ASP.NET-Web-API-CRUD-Operations

Angular CRUD operation using ASP .NET Web API with Entity Framework Code first approach in SQL Server. Beginners guide to Read more

How to use angular material in angular

How to use angular material in angular

In this article we are going to discuss how to use angular material in angular 9 application. If you are new to angular then explore our Angular Series. If you miss our previous article of angular Routing then please follow the link.

Let’s Create sample angular 9 application and there we use material design. We have create some controls of materiel theme in this example. To create angular 9 application use the below command.

Create Angular Project

The below command is use if are freshly start the angular and install updated angular CLI version.

npm install -g @angular/cli@

To create a new project add the below command with Routing as YES and style as CSS. ng-material-design here our project name, you can create a project according to your choice.

ng new ng-material-design

Add the material design into angular

Using below command we can add the material design into angular 9 application.

ng add @angular/material
install material design in angular 9

On the above image while we run the command it prompt that which material theme want to install. In our case we use “Indigo/Pink”. You can install any other theme according to your choice just navigate to the themes.

material theme

On the above image you can see after installing the “Indigo/pink” theme the material package also added into package.json, angualr.json and styles.css automatically.

After adding the theme you can find the css in angular.json file like below;

"styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import {MatSliderModule} from '@angular/material/slider';
import {MatSelectModule} from '@angular/material/select';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSliderModule,
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MatSelectModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Code Explanation

We need to add the several modules into app.module.ts to access in HTML page. After importing the module we need to add into Imports[].

Remove all the predefined HTML in app.componenet.html file then add the materiel design like below;

<div class="container mt-5">
  <h1>Angular Basic Material Design form</h1>
  <h2>Slider</h2>
  <mat-slider min="1" max="100" step="1" value="1"></mat-slider>
  <h2>TextBox</h2>
   <input matInput placeholder="Simple Input" [(ngModel)]="title" class="form-control">
   <h2>Dropdown</h2>
   <mat-form-field appearance="fill">
    <mat-label>Favorite food</mat-label>
    <mat-select>
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <h2>Icon</h2>
  <mat-icon>home</mat-icon>
  <h2>Button</h2>
  <button mat-raised-button>Material button</button>
</div>

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

interface Food {
  value: string;
  viewValue: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-material-design';
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
}

Code Explanation

app.component.html

  • Here we take a basic example to create a materiel text box. Matinput is responsible for to convert the textbox into material text-box with [(ngModel)] is used to bind the title.
  • Then we create the material slider, Icon, Button etc..
  • We create a dummy drop down to access the value from app.component.ts. In the mat-option we iterate the result and bind the data into dropdown.

app.component.ts

  • Here we declare title value that should append on the text box.
  • Then we added a Interface of Food that hold the fruits information.
  • Finally, we declare a foods list that contain food array.
  • Consuming the foods list the drop-down can bind.

That’s it run the application and see the output like below;

Summary

So far this article we discuss how to use material design in angular 9. If have any suggestion about this article please give your feedback.

That’s a wrap for this article. I hope that it cleared about How to use angular material in angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Angular 10 with ASP.NET Web API-CRUD Operations
Angular-10-with-ASP.NET-Web-API-CRUD-Operations

Angular CRUD operation using ASP .NET Web API with Entity Framework Code first approach in SQL Server. Beginners guide to Read more

How to create custom pipes in Angular
How to create custom pipes in Angular

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are Read more

Pin It on Pinterest