話不多說,看代碼:
import { Directive, ElementRef, HostListener,Input, Renderer, Component } from '@angular/core';
import { Platform } from 'ionic-angular';
@Directive({ selector: '[autoAreatext]' })
export class autoAreatextDirective {
minHeight:string;
@Input('autoAreatext') height: string;
constructor(private el: ElementRef, private renderer: Renderer, public platform: Platform) {
this.platform.ready().then(() => {
this.minHeight = el.nativeElement.clientHeight;
});
}
auto(){
if(!this.minHeight){
return false
}
this.renderer.setElementStyle(this.el.nativeElement, 'height', this.minHeight+'px');
if(this.el.nativeElement.scrollHeight>this.minHeight){
this.renderer.setElementStyle(this.el.nativeElement, 'height', this.el.nativeElement.scrollHeight+'px');
this.renderer.setElementStyle(this.el.nativeElement, 'overflow', 'hidden');
}
}
@HostListener('paste') onPaste() {
this.auto();
}
@HostListener('cut') onCut() {
this.auto();
}
@HostListener('keydown') onKeydown() {
this.auto();
}
@HostListener('keyup') onKeyup() {
this.auto();
}
@HostListener('focus') onFocus() {
this.auto();
}
@HostListener('blur') onBlur() {
this.auto();
}
}
這個指令寫在textarea上面就行了,記得在app.module里面也定義一下。如圖:
這個文本域高度就自適應了。指令里定義了一個變量,取的是指令上寫的值,這里沒有用到,自己可以看需要拓展,比如設置最大高度之類的。