DEV Community

Cover image for Angular Pipe Character Counter
Renan Ferro
Renan Ferro

Posted on • Edited on

7 1

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';

@Pipe({
  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:

 typescript
@NgModule({
  declarations: [
    MySiteComponent,
    CounterCharactersPipe
  ],
  imports: [
    ...
  ]
})


Enter fullscreen mode Exit fullscreen mode
  • And finally, We can just use the custom pipe in our span!

 html
 <app-form-input-text labelDescription="Name"                                
                      formControlName="name"
                      inputName="Name"
                      #name                                                                                                                                  
                      [classInput]="applyError('name')"                                       
                      [control]="getField('name')"></app-form-input-text>
<span class="d-block">
  {{ this.name.value | counterCharacters }}/30
</span>


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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay