Как заставить Textarea увеличить высоту, когда пользователь вставляет разрыв строки? - PullRequest
0 голосов
/ 21 октября 2019

Вот Stackblitz проблемы.

Получение помощи от этого сообщения . Я сделал это, чтобы отрегулировать высоту;если введено более 107 символов, оно увеличивается от 3 до 5 строк. и после этого он добавляет полосу прокрутки, и пользователь может прокручивать оставшуюся часть содержимого.

Мое требование заключается в том, что он также должен вести себя так же, когда пользователь ставит разрывы строки. Если пользователь вводит 1, то нажимает клавишу ввода, затем 2, затем вводит 3 и вводит снова при следующем вводе, он должен изменить размер и увеличить высоту для 4-го ряда. Как я могу это сделать?

import {Component, ElementRef, ViewChild} from '@angular/core';

/**
 * @title Basic Inputs
 */
@Component({
  selector: 'input-overview-example',
  styles: `
::ng-deep .commentText {
  width: 100% !important;
  min-height: 59px;
  max-height: 100px;
  border-radius: 4px !important;
  border: solid 1px #bab8b8 !important;
  font-size: 13px;
  color: #000000;
  padding: 6px;
  resize: none;
}
`,
  template: '
<div style="width: 250px">

    <textarea class="commentText"
                      #commentTextArea
                      [style.height]="textAreaHeight"
                      (input)="textAreaResize()"
                      [maxLength]="300"
                      [(ngModel)]="commentTextValue"
                      placeholder="Type your Comment">
  </textarea>

</div>

',
})
export class InputOverviewExample {
  @ViewChild('commentTextArea', {static: false}) commentTextArea: ElementRef;
  textAreaHeight: any;
  commentTextValue: string;


  textAreaResize() {
    // this.changeDetectorRef.detectChanges();


    const textArea: HTMLTextAreaElement = this.commentTextArea.nativeElement;
    if (this.commentTextValue || this.commentTextValue === '') {
      if (this.commentTextValue.length < 107) {
        this.textAreaHeight = '59px';
      } else {
        const height = Math.max(57, Math.min(textArea.scrollHeight, 98));
        textArea.style.overflow = (textArea.scrollHeight > height ? 'auto' : 'hidden');
        this.textAreaHeight = height + 'px';
      }
    }
  }

}


/**  Copyright 2019 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */

1 Ответ

1 голос
/ 21 октября 2019

Используйте cdkTextareaAutosize декоратор на текстовой области для увеличения высоты при вводе или разрыве строки.

<textarea class="commentText"
     #commentTextArea
     cdkTextareaAutosize
     [style.height]="textAreaHeight"
     (input)="textAreaResize()"
     [maxLength]="300"
     [(ngModel)]="commentTextValue"
     placeholder="Type your Comment">
</textarea>
...