【问题标题】:How to force Textarea to increase height when a user puts in a line break?当用户换行时,如何强制 Textarea 增加高度?
【发布时间】:2019-10-21 16:34:57
【问题描述】:

Here is the Stackblitz的问题。

从这个post 获得帮助。我已经调整了高度;当输入超过 107 个字符时,它会从 3 行扩展到 5 行。之后它会添加一个滚动条,用户可以滚动其余内容。

我的要求是当用户 换行。如果用户输入 1 然后按 Enter 键然后按 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 */

【问题讨论】:

    标签: javascript angular angular-material textarea


    【解决方案1】:

    在 textarea 上使用 cdkTextareaAutosize 装饰器来增加输入或换行符的高度。

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

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多