DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Angular Pipe Character Counter
Renan C. Ferro
Renan C. 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';

@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:
@NgModule({
  declarations: [
    MySiteComponent,
    CounterCharactersPipe
  ],
  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"                                
                      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!

Top comments (0)

🌚 Turn on dark mode

πŸ”  Change your default font

πŸ“š Adjust your experience level to see more relevant content

Β 

Head to your account's Settings to do all this and more.