【问题标题】:Angular - Textarea directive maxHeightAngular - Textarea 指令 maxHeight
【发布时间】:2018-12-23 20:26:01
【问题描述】:

目前,我正在使用以下代码编写一个指令,用于根据用户输入自动调整文本区域的大小:

import { ElementRef, HostListener, Directive, OnInit } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class Autosize implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}

但是,我一直在努力增加最大高度。因为如果用户输入了很长的消息,文本区域将在视图之外展开。有没有办法让它扩展直到 textarea 的行达到 3 ,然后就像一个普通的文本区域一样工作,里面有滚动和固定的高度?

【问题讨论】:

    标签: angular ionic-framework textarea directive


    【解决方案1】:

    您可以将 maxHeight 添加到您的元素样式中。

    Here's a working example.

    adjust():void {
       const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
       //textArea.style.overflow = 'hidden';
       textArea.style.height = 'auto';
       textArea.style.height = textArea.scrollHeight + 'px';
       textArea.style.maxHeight = '100px';
    }
    

    【讨论】:

    • 我刚刚尝试使用它,但是maxHeight 似乎并不适用。文本区域仍然扩展超过 100 像素。
    • 您查看我提供的链接了吗?你能不能也创建一个让我看看?
    • 成功了!谢谢!
    • 太好了,很高兴为您提供帮助!
    【解决方案2】:

    尝试为您的元素设置一个 css 属性 max-height。

    【讨论】:

    • 我试过了。但是,maxHeight 似乎并不适用。 Textarea 仍然能够扩展超过给定的 maxHeight。
    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多