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

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

问题描述

我正在尝试创建一个 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元素来获取文本宽度,这有点hacky.肯定有不止一种方法来计算字符串的宽度,包括 这个.

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天全站免登陆