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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM