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!
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;
}
}
- After that, we need to declare the pipe in our module:
typescript
@NgModule({
declarations: [
MySiteComponent,
CounterCharactersPipe
],
imports: [
...
]
})
- 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>
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)