I am currently facing the following problem. I have a textarea
and I want not only to limit the size of the textarea
with the default attributes rows
and cols
, but I also want to prevent the user from entering more characters than the ones defined in those attributes. I have a somewhat working solution but I am not too happy with it. Maybe you have some suggestions how to improve the solution
HTML
<textarea rows="2" cols="10" (keyup)="limitTextArea($event)"></textarea>
JS
limitTextArea(evt: KeyboardEvent) {
let textarea = evt.target as any
let maxRows: number = textarea.rows;
let maxColumns: number = textarea.cols;
let newContent: string = (textarea.value as string)
.split('\n')
.filter((val, row) => row < maxRows)
.map(val => val.slice(0, maxColumns))
.join('\n');
textarea.value = newContent;
}
Now there are several problems with this solution.
- It is being called by the
keyup
-Event. So the user will always see the character he or she typed before it disappears again. - I kind of mess around with the whole 2 way data binding principle by setting
textarea.value
- I am using
any
as Type for thetextarea
which I really don't like. If I am using TypeScript I want to use Types.
Any ideas how to solve this?