angular-directive - 无法在 Ionic 4 中获取 ion-textarea 的 nativeElement 来设置高度

标签 angular-directive ionic4 elementref

我有一个自定义指令来调整 ion-textarea 高度以在输入文本时自动调整高度,而不是设置固定的行高或在 textarea 填满时使用丑陋的滚动条。

在 Ionic-4 中,我无法获得 ion-textarea 的 html textarea 的 nativeElement。任何帮助都会很棒

它在 Angular 6 和 Ionic 4 上运行,但是当我尝试获取 this.element.nativeElement.getElementsByTagName('textarea')[0] 时,它始终未定义,因此我无法以编程方式设置高度。

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

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class AutosizeDirective implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  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';
  }
}

由于 const textArea 总是返回未定义,我无法将高度设置为跟随滚动高度以防止滚动条。

有人能在 Ionic-4 中做到这一点吗?根据上述代码在 Ionic-3 中查看工作示例。

谢谢 罗伊

最佳答案

下面的代码可以解决您的问题。

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

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class AutoSizeDirective implements AfterViewInit {
  readonly defaultHeight = 64;

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

  constructor(private element: ElementRef) {}

  ngAfterViewInit() {
    this.adjust();
  }

  adjust(textArea?: HTMLTextAreaElement) {
    textArea = textArea || this.element.nativeElement.querySelector('textarea');

    if (!textArea) {
      return;
    }

    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = (textArea.value ? textArea.scrollHeight : defaultHeight) + 'px';
  }
}

Usage: <ion-textarea autosize></ion-textarea>

我已经在 Ionic 4.0.2/Angular 7.2.6 上确认了.

问候。

关于angular-directive - 无法在 Ionic 4 中获取 ion-textarea 的 nativeElement 来设置高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174031/

相关文章:

angular - 当组件更新值时,指令@Input 变量没有得到更新

angular - angular2 中是否有 ng-disabled 的替代方案?

css - 将 css 分配给 *ngFor item 的值

html - 如何在 ionic 4 中将 ionic 按钮居中?

javascript - 运行 ngserve Angular5 时出错

angular - 使用 mousedown HostListener 移动元素(拖放)

css - IONIC4 : how to use cssClass for Loading , 它不起作用

angular - 构建 Angular 应用程序后,elementRef 为空

javascript - 空数组上的 Angular 双向数据绑定(bind)不起作用