ionic2踩坑之文本域自适应高度(自定义指令,适用angular2)

话不多说,看代码:

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里面也定义一下。如图:

这个文本域高度就自适应了。指令里定义了一个变量,取的是指令上写的值,这里没有用到,自己可以看需要拓展,比如设置最大高度之类的。

posted @ 2017-02-28 17:56  eccainiao  阅读(4300)  评论(0编辑  收藏  举报