美文网首页
ionic textarea自适应高度 指令

ionic textarea自适应高度 指令

作者: Bager | 来源:发表于2020-04-07 08:52 被阅读0次

原理就是监听input事件,每次输入后执行adjust方法调整样式。

1、创建文件

ionic g directive autosize

2、编辑文件

import { Directive, ElementRef, HostListener } from '@angular/core';
 
@Directive({
  selector: '[autosize]' // Attribute selector
})
export class AutosizeDirective {
 
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }
 
  constructor(public element:ElementRef) {
    console.log('Hello AutosizeDirective Directive');
  }
 
  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }
 
  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}

3、使用方法

<ion-item>
    <ion-textarea name="test" [(ngModel)]="text" autosize></ion-textarea>
</ion-item>

相关文章

网友评论

      本文标题:ionic textarea自适应高度 指令

      本文链接:https://www.haomeiwen.com/subject/wbtgphtx.html