3

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.

  1. It is being called by the keyup-Event. So the user will always see the character he or she typed before it disappears again.
  2. I kind of mess around with the whole 2 way data binding principle by setting textarea.value
  3. I am using any as Type for the textarea which I really don't like. If I am using TypeScript I want to use Types.

Any ideas how to solve this?

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
relief.melone
  • 3,042
  • 1
  • 28
  • 57
  • 1
    have you tried maxlength and https://stackoverflow.com/questions/5271782/how-to-disable-the-resize-grabber-of-an-html-textarea? – ABOS Dec 11 '18 at 13:06
  • maxlength unfortunately just limits the amount of characters in total. it doesnt care about the characters per line – relief.melone Dec 11 '18 at 13:12
  • col specifies the chars per line. btw, have you tried the link above? – ABOS Dec 11 '18 at 13:14
  • 1
    As far as your `any` type goes, if you type the textarea as `let textarea = evt.target as HTMLTextAreaElement` you can remove your `string` casting for the textarea value. – garethdn Dec 11 '18 at 13:23
  • Thanks. That was the type i was looking for – relief.melone Dec 11 '18 at 14:17

1 Answers1

1

Logically, if you want 2 rows of 10 columns each, implies that you need 20 characters in total. So you can simply set maxlength="20". You may always change values accordingly...

You don't need to use keyup event in this scenario. Just use maxlength attribute & it will limit maximum characters to take from user & won't allow more than that for you.

See it running below -

/* disable textarea resizing */
textarea {
  resize: none;
}
<script src="https://unpkg.com/@angular/platform-browser-dynamic@7.0.1/bundles/platform-browser-dynamic.umd.js"></script>
<textarea rows="2" cols="10" maxlength="20"></textarea>
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56