ionic3 textarea 自适应指令

作者:猿奇
链接:www.jianshu.com/p/9d8c7b7558d8
來源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

如有疑问,可评论联系作者,热心解答,从不怼人。。。

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();
  }

  @Input('autoresize') maxHeight: number;
  
    constructor(public element: ElementRef) {
  }
  
    ngOnInit(): void {
        this.adjust();
  }
  
    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 使用示例: 
// html 使用示例: 

你可能感兴趣的:(ionic3 textarea 自适应指令)