【问题标题】:increase textarea size according to the size of the text in the angular根据角度文本的大小增加文本区域大小
【发布时间】:2022-01-08 01:35:30
【问题描述】:

目前正在使用以下代码来调整文本区域的大小

function autoResize(el){
  while (el.scrollHeight > el.offsetHeight){
    el.rows += 1;
  }
}

但只有当我将鼠标悬停在文本区域上时它才会调整大小

<textarea onmousemove="autoResize(this)"></textarea>

我想让它在我打开具有 textarea 的屏幕时自动调整大小。我已经尝试切换到 onload 但没有成功

【问题讨论】:

  • 将 autoResize() 添加到组件的 ngOnInit() 方法中,您也可以在 keyup 事件中调用它。
  • 我该怎么做?我是否必须将 autoResize() 函数放入 ngOninit() 中?

标签: javascript html angular


【解决方案1】:
export class TextAreaComponent extends OnInit { 
 @ViewChild('textarea', { read: ElementRef,static:true }) textarea: ElementRef; 
  @Input() value:string;
  rowCount: number;
  ngOnInit(): void {
    this._autoResize(this.textarea.nativeElement);
  }

  onKeyup(el) {
    this._autoResize(el);
  }
  private _autoResize(el) {
   while (el.scrollHeight > el.offsetHeight){
     el.rows += 1;
   }
  }  
}

textarea 组件的模板可能是这样的

<textarea
  #textarea
  [value]="!value ? '' : value"
  (keyup)="onKeyup(textarea)"
></textarea>

我为您创建了一些示例代码。 https://stackblitz.com/edit/angular-ivy-kxszjh?file=src%2Fapp%2Fapp.component.ts

【讨论】:

    猜你喜欢
    • 2016-06-17
    • 2013-03-24
    • 1970-01-01
    • 2012-06-27
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2012-11-23
    相关资源
    最近更新 更多