Published on

How to use custom pipes in Angular!

Basic diagram on how Angular pipes work👏

Figure 1: Basic diagram on how Angular pipes work👏

Do you know what Angular pipes are? How about Angular custom pipes? No? Well just keep reading to find out!

What are Angular Pipes?

Angular pipes are used to transform input data, whether that be dates, strings, floats, and other data for display in a specified output format. At their core, pipes are just functions that are used in template expressions to receive an input value and produce a transformed output.

Angular provides a plethora of built-in pipes for common data transformations such as the ones listed below:

  • DatePipe: Produces a data value based on locale rules
  • CurrencyPipe: Converts a number into a current string, which will be done according to locale rules
  • PercentPipe: Converts a number into a percentage string, done according to locale rule
  • LowerCasePipe: Coverts any text into all lower case letters

Angular Custom Pipes

Ok, now that you know what Angular pipes are, let's go over what custom pipes are: Custom pipes are pipes that implement the PipeTransform interface and provide the ability to use custom functionality that is not included in the Angular built-in pipes. For example: you could create a custom pipe to reverse a string, convert untrusted HTML into trusted and sanitized HTML, and covert any number into a currency value.

Custom pipe example:

Let's go over an Angular example project where we demonstrate the use of Angular custom pipes.

Start by creating a new Angular project and creating a component called word-form.

Then create a folder named pipes in the src/app path and run the following command to create a pipe named word-randomizer:

ng generate pipe word-randomizer

Inside the word-randomizer.pipe.ts file we can add the following code:

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

@Pipe({
  name: 'wordRandomizer'
})
export class WordRandomizerPipe implements PipeTransform {

  transform(value: string, ...args: unknown[]): unknown {
    if(value == ""){
      return "";
    }
    return this.scramble(value);
  }

  scramble(a: string){
    return a.split('').sort(function(){return 0.5-Math.random()}).join('');
  }

}

Basically the above logic will transform an inputted word as a scrambled version of itself which will be returned as output.

Next, let's build the word-form component by adding the following code to the word-form.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-word-form',
  templateUrl: './word-form.component.html',
  styleUrls: ['./word-form.component.css']
})
export class WordFormComponent implements OnInit {
  wordForm: FormGroup;
  randomWord: string = "";
  showRandomWord: boolean = false;

  constructor(private fb: FormBuilder) { }

  get f() { return this.wordForm.controls; }

  ngOnInit(): void {
    this.wordForm = this.fb.group({
      wordInput: [null, Validators.required]
    });
  }

  onSubmit(){
    if(this.wordForm.valid){
      this.randomWord = this.f.wordInput.value;
      this.showRandomWord = true;
    }
  }
}

And the following code for the word-form.component.html file:

<form class="form" [formGroup]="wordForm" (ngSubmit)="onSubmit()">
    <label for="wordInput" >Enter a word: </label>
    <br/>
    <input id="wordInput" name="wordInput" type="text" formControlName="wordInput" />
    <br/>
    <br/>
    <input type="submit" id="submitButton" />
    <h3 *ngIf="showRandomWord">Scrambled Word: {{ randomWord | wordRandomizer }}</h3>
</form>

A brief explanation as to what we just added: a form containing a single text input along with a submit button will be created in the word-form component. Once the user enters a word into the text input and clicks the submit button the submitted word will be transformed by the wordRandomizer custom pipe and outputted as a scrambled version of the original word. This scrambled word will appear below the submit button upon form submission

Finally, make sure to include the WordRandomizerPipe pipe in the app.module.ts file, so that our Angular application can reference it when we refer to it in the word-form.component.html file, like so:

@NgModule({
  declarations: [
    AppComponent,
    WordRandomizerPipe,
    WordFormComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now all we have to do is run our Angular application via npm start and navigate to http://localhost:4200 on our browser!🚀

Here is the wordRandomizer pipe in action:

Behold the power of Angular pipes!

Figure 2: Behold the power of Angular pipes!🔥

Conclusion

Congratulations! You now know what Angular pipes are and how to implement custom pipes in you Angular application. If you need access to the source code for this application you can access it by visiting it's GitHub link.

Well that's it for this post! Thanks for following along in this article and if you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on Twitter and GitHub, connect with me on LinkedIn, subscribe to my YouTube channel.