<textarea (ngModelChange)="onChange()" [(ngModel)]="val" (focus)="onChange()" (blur)="onChange()" #text class="autosize" maxlength={{maxlength}} rows="1" placeholder={{placeholder}}></textarea>
<!--text1为影子textarea 用于获取scrollHeight,并将值付给主textarea的height 实现auto resize -->
<textarea class="autosize hidden" rows="1" [value]="val" #text1 ></textarea>
:host {
display: flex;
justify-content: flex-start;
.autosize {
vertical-align: top;
padding: 7px 8px;
font-size: 12px;
width: 200px;
border-radius: 3px;
line-height: 14px;
position: relative;
outline: none;
resize: none;
box-sizing: border-box;
height: 32px;
transition: height 0.2s;
}
.hidden {
position: absolute;
left: -100px;
visibility: hidden;
overflow: hidden;
}
}
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnInit, Output, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'textarea-auto-resize',
templateUrl: './textarea-auto-resize.component.html',
styleUrls: ['./textarea-auto-resize.component.less'],
})
export class TextareaAutoResizeComponent implements OnInit, AfterViewInit {
@Input('max-height') maxHeight = 100; // 最大高度 默认 100
@Input('maxlength') maxlength = 500; // 最大字数 默认500
@Input('placeholder') placeholder: any; // placeholder 提示语
@Input('g') g: any;
@Input('el') el: any;
@Output('valChange') valChange = new EventEmitter();
@ViewChild('text') text: ElementRef;
@ViewChild('text1') text1: ElementRef;
@Input('value') val = '';
constructor(private rd2: Renderer2) {}
ngOnInit() {}
ngAfterViewInit() {
this.reset();
}
onChange() {
this.reset();
setTimeout(() => {
this.valChange.emit({
value: this.val,
g: this.g,
el: this.el,
});
this.reset();
}, 0);
}
/**
* @description: 改变textarea的高度
* @param {type}
* @return:
*/
reset() {
this.text1.nativeElement.style.width = this.text.nativeElement.scrollWidth + 2 + 'px';
if (this.text1.nativeElement.scrollHeight < this.maxHeight) {
this.text1.nativeElement.style.width = this.text.nativeElement.scrollWidth + 19 + 'px';
this.text.nativeElement.style.height = this.text1.nativeElement.scrollHeight + 2 + 'px';
} else {
this.text.nativeElement.style.height = this.maxHeight - 0 + 2 + 'px';
}
}
}
Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your team
https://serious-lose.notion.site/NG-Textarea-auto-resize-dacc0008c9474ba88972b9a4b7c9567f