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

问题描述 投票:1回答:2

我有一个自定义指令来调整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总是返回undefined我无法设置高度以跟随滚动高度以防止滚动条。

有没有人能够在Ionic-4中做到这一点?根据上面的代码看到了Ionic-3中的工作示例。

谢谢Rowie

angular-directive ionic4 elementref
2个回答
4
投票

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

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

用法:<ion-textarea autosize></ion-textarea>

我已经在Ionic 4.0.2/Angular 7.2.6上证实了这一点。

问候。


2
投票

这个软件包为我做了所有autosizing我的离子textareas https://github.com/chrum/ngx-autosize只是按照指南并让它工作,如果它无法将其导入app.module.ts然后尝试将其导入页面的模块,我个人需要如果你愿意,那就不知道了,但是包装是救命的

© www.soinside.com 2019 - 2024. All rights reserved.