2

I don't want to know how to set the visible number of rows.

I want to restrict the number of lines of text that a user can enter into a text area.

For example I want a maximum of 10 lines. If the user can enter 11 lines it will mess up the UI on other applications that use the data.

By lines I mean when the user enters a carriage return and starts on a new line. If you cut and paste the text from the text area into notepad on windows there should be no more than 10 lines. e.g. This description is 14 lines long (this does not included wrapped text).

I already know how to adjust visible rows and restrict character length.

EDIT: I have edited the title and description to try and make it clearer.

MadMac
  • 4,048
  • 6
  • 32
  • 69
  • https://stackoverflow.com/questions/6501043/limit-number-of-lines-in-textarea-and-display-line-count-using-jquery – 4b0 Aug 01 '19 at 07:52
  • Change your question title. You don't mean max rows as you explain in the description. Explain more about what you mean since it's apparently neither max rows nor max length (number of characters), but you still describe it as "maximum number of rows". – G. Tranter Aug 01 '19 at 14:27
  • @G.Tranter I have edited for clarity. Hopefully it makes sense now. – MadMac Aug 01 '19 at 21:36

2 Answers2

0

There is probably more than one way to do this, but an obvious - and relatively straightforward - one is to listen to input events on the text area and remove any line feed characters added over the limit. This is a generic solution - it isn't specific to Angular or Angular Material (but the code is TypeScript):

<textarea matInput (input)="limitLines($event, 5)"></textarea>

limitLines(event: InputEvent, maxLines: number) {
  let text = (event.target as HTMLTextAreaElement).value;
  if (text.length > 0) {
    const lineCount = 1 + text.replace(/[^\n]/g, '').length;
    if (lineCount > maxLines) {
      const textArray = text.split('\n');
      const newText = textArray.reduce((result, line, lineNum, array) => {
        if (lineNum < maxLines) {
          return result.concat('\n').concat(line);
        }
        return result.concat(line);
      });
      (event.target as HTMLTextAreaElement).value = newText;
    }
  }
}
G. Tranter
  • 16,766
  • 1
  • 48
  • 68
0

you can also check by counting "\n" on the string and if the count is > than max rows then call event.preventDefault();

<textarea
 (keydown.enter)="onKeydown($event)"
 class="form-control"
></textarea>

onKeydown(event: Event) {
   if(textBoxValue.split("\n").length >= maxRows) {
     event.preventDefault()
   }
}
Devan Madlani
  • 143
  • 1
  • 1
  • 15