ionic3 textarea 自适应指令 (实用、赞)

205 篇文章 0 订阅
175 篇文章 1 订阅

原文出处:https://www.jianshu.com/p/9a04aa0224ed  (建议阅读原文)

补充注意:
  首次调用时加上setTimeout似乎好点

  ngOnInit(): void {
        //this.adjust();
        //必须要setTimeout, 否则面异步取数据时,无法调整高度
        setTimeout(() => this.adjust(), 0);
    }


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();
        // 加上setTimeout似乎好点
        setTimeout(() => this.adjust(), 0);
    }

    @Input('autoresize') maxHeight: number;  
    constructor(public element: ElementRef) {
    }  

    ngOnInit(): void {
        //this.adjust();

        //加上setTimeout 似乎好点
        setTimeout(() => this.adjust(), 0);
    }
  
    private 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 使用示例: <ion-textarea autoresize [(ngModel)]="body"></ion-textarea>
// html 使用示例: <ion-textarea autoresize="100" [(ngModel)]="body"></ion-textarea>



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值