zoukankan      html  css  js  c++  java
  • 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";
            }
          });
        }
      }

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

     
     
  • 相关阅读:
    无法设置 / 添加网络打印机?报错 无法保持设置?
    tp剩余未验证内容-5
    再谈 iptables 防火墙的 指令配置
    tp剩余未验证内容-4
    tp剩余未验证内容-3
    CentOS7.4安装配置mysql8 TAR免安装版
    CentOS7中systemctl的使用与CentOS6中service的区别
    CentOS下如何查看并杀死僵尸进程
    CentOS SVN服务器管理多项目
    swoole+Redis实现实时数据推送
  • 原文地址:https://www.cnblogs.com/ywy8/p/13213942.html
Copyright © 2011-2022 走看看