动态将输入宽度扩展到字符串的长度 [英] Expand input width dynamically to the length of string

查看:179
本文介绍了动态将输入宽度扩展到字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个input字段,该字段至少随着用户输入的字符串的长度动态扩展宽度,甚至可能是多行. Angular Material 2中的 input 元素是否可以实现?

I am trying to create an input field that expands at least in width dynamically with the length of the string the user entered, probably even multiline. Is that possible with an input element in Angular Material 2?

使用Angular Material 2中的textarea字段,我仅使用以下代码设法扩大了textarea的高度,而不是其宽度:

With the textarea field from Angular Material 2 I only managed to expand the textarea in height, not in width with the following code:

<mat-form-field (keydown.enter)="onEnter()" 
                floatPlaceholder="never">
  <textarea matInput 
            placeholder="Autosize textarea" 
            matTextareaAutosize
            matAutosizeMinRows="1" 
            matAutosizeMaxRows="8">
  </textarea>
</mat-form-field>

也在StackBlitz上 .

如果是textarea,则scrollbar应该是不可见的或由较小的代替.最重要的是,按 Enter 不应创建新行,而仅触发操作.

In case of the textarea the scrollbar should be invisible or replaced by a smaller one. And most important pressing Enter should not create a new line but trigger an action only.

推荐答案

您可以使用ngStyle将mat-form-field的宽度绑定到计算出的值,并在输入上使用input事件设置该值.例如,这是一个输入,其宽度跟随文本宽度超过64px:

You can use ngStyle to bind width of the mat-form-field to a calculated value, and use the input event on the input to set that value. For example, here's an input who's width follows the text width over 64px:

<mat-form-field [ngStyle]="{'width.px': width}">
    <input #elasticInput matInput (input)="resize()">
</mat-form-field>
<span #hiddenText style="visibility: hidden; white-space: pre;">{{elasticInput.value}}</span>

export class InputTextWidthExample {

    @ViewChild('hiddenText') textEl: ElementRef;

    minWidth: number = 64;
    width: number = this.minWidth;

    resize() {
        setTimeout(() => this.width = Math.max(this.minWidth, this.textEl.nativeElement.offsetWidth));
    }
}

很明显,此示例使用一个隐藏的span元素来获取文本宽度,这有点麻烦.当然,有多种方法可以计算字符串的宽度,包括.

Obviously, this example uses a hidden span element for getting the text width, which is a little hacky. There is surely more than one way to calculate a string's width, including this.

这是Stackblitz上的示例.

这篇关于动态将输入宽度扩展到字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆