从此post获得帮助。我已经调整好高度了。输入超过107个字符时,它将从3行扩展到5行。然后添加滚动条,用户可以滚动其余内容。
我的要求是,当用户使用时,其行为也应相同 换行。如果用户输入1,则按Enter键,然后按2,然后输入3,然后在下一个输入上再次输入,它应该调整大小并增加第四行的高度。我该怎么办?
import {Component, ElementRef, ViewChild} from '@angular/core';
/**
* @title Basic Inputs
*/
@Component({
selector: 'input-overview-example',
styles: `
::ng-deep .commentText {
width: 100% !important;
min-height: 59px;
max-height: 100px;
border-radius: 4px !important;
border: solid 1px #bab8b8 !important;
font-size: 13px;
color: #000000;
padding: 6px;
resize: none;
}
`,
template: '
<div style="width: 250px">
<textarea class="commentText"
#commentTextArea
[style.height]="textAreaHeight"
(input)="textAreaResize()"
[maxLength]="300"
[(ngModel)]="commentTextValue"
placeholder="Type your Comment">
</textarea>
</div>
',
})
export class InputOverviewExample {
@ViewChild('commentTextArea', {static: false}) commentTextArea: ElementRef;
textAreaHeight: any;
commentTextValue: string;
textAreaResize() {
// this.changeDetectorRef.detectChanges();
const textArea: HTMLTextAreaElement = this.commentTextArea.nativeElement;
if (this.commentTextValue || this.commentTextValue === '') {
if (this.commentTextValue.length < 107) {
this.textAreaHeight = '59px';
} else {
const height = Math.max(57, Math.min(textArea.scrollHeight, 98));
textArea.style.overflow = (textArea.scrollHeight > height ? 'auto' : 'hidden');
this.textAreaHeight = height + 'px';
}
}
}
}
/** Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license */
答案 0 :(得分:1)
在文本区域上使用cdkTextareaAutosize
装饰器以增加输入或换行符的高度。
<textarea class="commentText"
#commentTextArea
cdkTextareaAutosize
[style.height]="textAreaHeight"
(input)="textAreaResize()"
[maxLength]="300"
[(ngModel)]="commentTextValue"
placeholder="Type your Comment">
</textarea>