NG Textarea-auto-resize

<textarea (ngModelChange)="onChange()"  [(ngModel)]="val"  (focus)="onChange()" (blur)="onChange()" #text class="autosize" maxlength={{maxlength}} rows="1" placeholder={{placeholder}}></textarea>
<!--text1为影子textarea 用于获取scrollHeight,并将值付给主textarea的height 实现auto resize -->
<textarea class="autosize hidden"  rows="1" [value]="val" #text1 ></textarea>
:host {
  display: flex;
  justify-content: flex-start;
  .autosize {
    vertical-align: top;
    padding: 7px 8px;
    font-size: 12px;
    width: 200px;
    border-radius: 3px;
    line-height: 14px;
    position: relative;
    outline: none;
    resize: none;
    box-sizing: border-box;
    height: 32px;
    transition: height 0.2s;
  }

  .hidden {
    position: absolute;
    left: -100px;
    visibility: hidden;
    overflow: hidden;
  }
}
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnInit, Output, Renderer2, ViewChild } from '@angular/core';

@Component({
  selector: 'textarea-auto-resize',
  templateUrl: './textarea-auto-resize.component.html',
  styleUrls: ['./textarea-auto-resize.component.less'],
})
export class TextareaAutoResizeComponent implements OnInit, AfterViewInit {
  @Input('max-height') maxHeight = 100; // 最大高度 默认 100
  @Input('maxlength') maxlength = 500; // 最大字数 默认500
  @Input('placeholder') placeholder: any; // placeholder 提示语
  @Input('g') g: any;
  @Input('el') el: any;
  @Output('valChange') valChange = new EventEmitter();
  @ViewChild('text') text: ElementRef;
  @ViewChild('text1') text1: ElementRef;
  @Input('value') val = '';

  constructor(private rd2: Renderer2) {}

  ngOnInit() {}
  ngAfterViewInit() {
    this.reset();
  }

  onChange() {
    this.reset();
    setTimeout(() => {
      this.valChange.emit({
        value: this.val,
        g: this.g,
        el: this.el,
      });
      this.reset();
    }, 0);
  }
  /**
   * @description: 改变textarea的高度
   * @param {type}
   * @return:
   */
  reset() {
    this.text1.nativeElement.style.width = this.text.nativeElement.scrollWidth + 2 + 'px';
    if (this.text1.nativeElement.scrollHeight < this.maxHeight) {
      this.text1.nativeElement.style.width = this.text.nativeElement.scrollWidth + 19 + 'px';
      this.text.nativeElement.style.height = this.text1.nativeElement.scrollHeight + 2 + 'px';
    } else {
      this.text.nativeElement.style.height = this.maxHeight - 0 + 2 + 'px';
    }
  }
}

 Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your teamhttps://serious-lose.notion.site/NG-Textarea-auto-resize-dacc0008c9474ba88972b9a4b7c9567f

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值