Search code examples
angulartypescripttextarealinemaxlength

Max Length for Each Line in Textarea


I use Angular 5.2.6 and adding some form file in my html. There is a textarea in that form and I want to limit its maximum chars in each row.

Here is the HTML part:

<textarea siInput [(ngModel)]="myTextarea" style="resize:none;  white-space: nowrap;" rows="20" (ngModelChange)="`handleTextareaChange`($event)" (keydown)="onKeydown($event)" maxlength="{{maxlength}}" id="textID"></textarea>

I have defined maxlength and maxLineLength in component class. Also here is the methods I have tried so far :)

onKeydown(event) {
   if (event.key === "Enter") {
     this.pressEnter = true;
     this.maxlength += this.maxLineLength + 1;
   }
   else {
     this.pressEnter = false;
   }
}

handleTextareaChange(text) {

   var mainString = text;
   var allLines = mainString.split("\n");

   var len = mainString.length;
   var numberOfLines = allLines.length;
   var indexOfCurrentLine = allLines.length - 1;

   var previousLines = "";
   for (var i = 0; i < indexOfCurrentLine; i++) {
     previousLines += allLines[i];
   }
}

If you have any ideas, please share with me.

Thanks.


Solution

  • I have found the solution. I did not use maxlength properties, and created new function in component.ts

    here is HTML:

    <textarea siInput [(ngModel)]="myTextarea" style="resize:none;  white-space: both;" rows="20" (keyup)="onKeyAction()"(keydown)="onKeyAction()" id="textID" maxlength="{{maxTextAreaLength}}"></textarea>
    

    and here is the funtion in component:

    this.maxTextLineLength: number = 50;
    onKeyAction() {
        if (this.myTextarea) {
          var lines = this.myTextarea.split(/(\r\n|\n|\r)/gm);
          for (var i = 0; i < lines.length; i++) {
            if (lines[i].length >= this.maxTextLineLength) {
              lines[i] = lines[i].substring(0, this.maxTextLineLength);
            }
          }
          this.myTextarea = lines.join('');
        }
    }