1

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.

Süleyman K
  • 309
  • 1
  • 8
  • 17

2 Answers2

2

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('');
    }
}
Süleyman K
  • 309
  • 1
  • 8
  • 17
-1

Here is the solution for control in maxlength,

you have to pass like this in your textarea tag,

[maxLength]="textareaLength"

either you can use like this also,

[attr.maxlength]="maxLength" 

you can set this variable value in typescript,

For more Reference,

Angular2 maxLength for textarea as variable

http://embed.plnkr.co/CkAbaQLQVndoC47OtQRF/

I hope it's solve your problem.

Karnan Muthukumar
  • 1,843
  • 1
  • 8
  • 15
  • I have already used as maxlength="{{maxlength}}" :) I want to limit for each row... When enter key is used (new line), it can be typed again in that new line – Süleyman K Jul 15 '18 at 15:49