原文出处:https://www.jianshu.com/p/9a04aa0224ed (建议阅读原文)
补充注意:
首次调用时加上setTimeout似乎好点
ngOnInit(): void {
//this.adjust();
//必须要setTimeout, 否则面异步取数据时,无法调整高度
setTimeout(() => this.adjust(), 0);
}
Auto resize directive for TextAreas in Angular 2/4
新建directive
(记得在app.module.ts里面注入directives.module)
$ ionic g directive Autoresize_textarea
Autoresize-textarea.ts写入指令(自适应、配置最大高度及封装指令)
// An autoresize directive that works with ion-textarea in Ionic 3
// Based on https://www.npmjs.com/package/angular2-autosize
import { Directive, HostListener, ElementRef, Input } from "@angular/core";
@Directive({
selector: "ion-textarea[autoresize]" // Attribute selector
})
export class AutoresizeDirective {
@HostListener('input', ['$event.target'])
onInput(textArea: HTMLTextAreaElement): void {
// this.adjust();
// 加上setTimeout似乎好点
setTimeout(() => this.adjust(), 0);
}
@Input('autoresize') maxHeight: number;
constructor(public element: ElementRef) {
}
ngOnInit(): void {
//this.adjust();
//加上setTimeout 似乎好点
setTimeout(() => this.adjust(), 0);
}
private adjust(): void {
let ta = this.element.nativeElement.querySelector("textarea"),
newHeight;
if (ta) {
ta.style.overflow = "hidden";
ta.style.height = "auto";
if (this.maxHeight) {
console.log('this.maxHeight',this.maxHeight)
newHeight = Math.min(ta.scrollHeight, this.maxHeight);
console.log('newHeight',newHeight)
}
else {
newHeight = ta.scrollHeight;
}
ta.style.height = newHeight + "px";
}
}
}
html 使用示例:
// html 使用示例: <ion-textarea autoresize [(ngModel)]="body"></ion-textarea>
// html 使用示例: <ion-textarea autoresize="100" [(ngModel)]="body"></ion-textarea>
作者:猿奇
链接:https://www.jianshu.com/p/9a04aa0224ed
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。