将输入宽度动态扩展到字符串的长度

Nig*_*ain 6 css angular-material2 angular angular-animations angular5

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

使用textareaAngular Material 2 中的字段,我只能使用以下代码扩展 textarea 的高度,而不是宽度:

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

也在 StackBlitz 上

在的情况下textareascrollbar应该是不可见或通过一个较小的一个替代。最重要的按下Enter不应该创建一个新行,而应该只触发一个动作。

Nae*_*ard 7

简单且唯一的模板解决方案:

<mat-form-field
  [ngStyle]="{'width.ch': inputText.value.length, 'min-width.ch': 10}"> 
  <input  #inputText  matInput>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)


G. *_*ter 6

您可以使用 ngStyle 将 mat-form-field 的宽度绑定到计算值,并使用输入上的输入事件来设置该值。例如,以下输入的宽度遵循超过 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,这个示例使用隐藏的 span 元素来获取文本宽度,这有点 hacky。计算字符串宽度的方法肯定不止一种,包括this

这是 Stackblitz 上的示例