DEV Community

Cover image for Angular Pipe Character Counter
Renan Ferro
Renan Ferro

Posted on • Updated on

Angular Pipe Character Counter

Have you ever needed a counter to get the number of characters in an input field and show the value in a label below the input, for example!?

It's normal to see that in a form field, like the image below!

Image description

So to resolve this "problem" I created a simple Angular pipe for do it!

  • First I created the Pipe:
import { Pipe, PipeTransform } from '@angular/core';

  name: 'counterCharacters'
export class CounterCharactersPipe implements PipeTransform {

  transform(value: string, ...args: unknown[]): number {
    if (value) {
      return value.length;

    return 0;

Enter fullscreen mode Exit fullscreen mode
  • After that, we need to declare the pipe in our module:
  declarations: [
  imports: [
Enter fullscreen mode Exit fullscreen mode
  • And finally, We can just use the custom pipe in our span!
 <app-form-input-text labelDescription="Name"                                
<span class="d-block">
  {{ | counterCharacters }}/30
Enter fullscreen mode Exit fullscreen mode

And now when we insert the value, the span tag show us the length of our input value!

That's it, thanks for reading!

Top comments (0)