ionic3如何让ion-textarea高度根据内容自适应

ionic3实现这个需要自定义指令,ionic4官网有个属性(点我直达ionic4官网API),直接使用即可,如图:

今天主要记录下ionic3我是怎么实现ion-textarea高度自适应的。

1.创建指令

ionic g  directive  Autoresize_textarea

2.编辑指令

import { Directive, HostListener, ElementRef } from "@angular/core";

/**
 * 控制ion-textarea高度自适应的指令,在需要使用该指令的路由中添加这个指令,并在 
 * <ion-textarea>中使用,
 * 如:<ion-textarea autoresize></ion-textarea>
 * @author ywy
 * @date 2020-06-30
 */
@Directive({
  selector: "ion-textarea[autoresize]" // Attribute selector
})
export class AutoresizeTextareaDirective {

  @HostListener('input', ['$event.target'])
  onInput(textArea: HTMLTextAreaElement): void {
    this.adjustHeight();
  }

  constructor(public element: ElementRef) { }

  ngOnInit(): void {
    this.adjustHeight();
  }

  adjustHeight(): void {
    let node = this.element.nativeElement.querySelector("textarea");
    if (node) {
      node.style.height = node.scrollHeight + "px";
    }
  }

}

3.在需要使用该指令的页面路由中添加并声明此指令,如图:

  4.在htmlion-textarea中添加指令autoresize

<ion-textarea placeholder="请输入" [(ngModel)]="content" autoresize></ion-textarea>

到这里,我们已经实现了ion-textarea的高度根据内容自适应的功能,但是还存在一个问题,就是回显的时候并没有自适应。这里我通过在ts触发自适应代码解决。

1.在使用该指令的ts中引入ElementRef

import { Component, ElementRef } from '@angular/core';

2.在构造方法中声明

constructor(
    public element: ElementRef
) { }

3.利用ionic的生命周期

  ionViewDidEnter() {
    setTimeout(() => {
      this.textareaAutoHeight();
    }, 1000);
  }

  textareaAutoHeight(){
    let nodeList = this.element.nativeElement.querySelectorAll("textarea");
    if (nodeList.length > 0) {
      nodeList.forEach(element => {
        if (element) {
          element.style.height = element.scrollHeight + "px";
        }
      });
    }
  }

如此回显也会自适应了,完结~撒花~❀

 
 
原文地址:https://www.cnblogs.com/ywy8/p/13213942.html