4 textarea resize refresh dynamic angular
我使用以下指令允许根据用户输入自动调整文本区域的大小:
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.height = 'auto';
textArea.style.height = textArea.scrollHeight + "px";
textArea.style.maxHeight = '100px';
}
}
Run Code Online (Sandbox Code Playgroud)
它按预期工作,但是当手动删除该文本区域内的文本时,文本区域不会自动调整大小。
例如,如果分配给该文本区域的 [(ngModel)] 变量被分配了不同的字符串或空字符串,则文本区域的高度将不会自动调整大小。用户需要重新开始输入以使 textarea 相应地调整大小。
什么是解决这个问题的好方法?
Cht*_*lek 10
我正在使用这种简单的方法,当文本被删除时,textarea 确实会缩小:
<textarea (keyup)="autoGrowTextZone($event)"></textarea>
Run Code Online (Sandbox Code Playgroud)
和
autoGrowTextZone(e) {
e.target.style.height = "0px";
e.target.style.height = (e.target.scrollHeight + 25)+"px";
}
Run Code Online (Sandbox Code Playgroud)
尝试添加这样的内容:
ngAfterContentChecked(): void {
this.adjust();
}
Run Code Online (Sandbox Code Playgroud)
或者只是使用这个库:ngx-autosize :)
更新
ngAfterContentChecked 挂钩的解决方案仍然有效,但如果使用太频繁,可能会影响应用程序速度......
另一种方法是将 ngModel 视为输入,这将让您依赖 ngOnChanges 挂钩,因此在您的指令中尝试添加:
...
@Input('ngModel') text: any;
...
ngOnChanges(changes) {
if (changes.text) {
this.adjust();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8352 次 |
最近记录: |