Reputation: 580
I try to show current number of characters inside a textarea, here is my code:
HTML
<div class="form-group col-md-12">
<textarea pInputTextarea placeholder="Write something..."
maxlength="50" (keydown.backspace)="onKeydown($event)"
(keypress)="maxLenght($event)" formControlName="addNotes" class="addNotes">
</textarea>
<span>{{notesLength}}/50</span>
</div>
Typescript
notesLength: number;
...
maxLenght(event: any) {
console.log('Key press', event);
this.notesLength = event.target.textLength;
}
onKeydown(event: any) {
this.notesLength = event.target.textLength;
}
The problem here is when I type the first letter even though the console.log()
shows that the event.target.textLength
is 1
the value of this.notesLength
remains 0
and always when typing the this.notesLength
is one character behind. Can anyone explain this and maybe give my any help?
Upvotes: 0
Views: 1100
Reputation: 3433
The problem here is that you are using keydown
. This even will fire the callback before the key value is registered in the text-area
.
To fix this simply change to event to keyUp
. This event, instead, will fire the callback after the value is registered in the text-area
and your total will show exactly the excepted result.
Bonus Tip
Using keyUp
will also handle properly some operations like deleting one character at time or, for example, with some combinations like CTRL + A
-> backspace
/ canc
/ CTRL + X
Upvotes: 2