首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将Ionic 4中的离子文本区域的nativeElement设置为高度

无法将Ionic 4中的离子文本区域的nativeElement设置为高度
EN

Stack Overflow用户
提问于 2019-01-13 23:02:20
回答 2查看 2.7K关注 0票数 2

我有一个自定义指令来调整离子文本区域的高度,使其在输入文本时自动调整高度,而不是设置固定的行高,或者在文本区域填充时设置难看的滚动条。

在Ionic-4中,我无法获得离子文本区域的html文本区域的nativeElement。任何帮助都是很好的

它运行在角度6和离子4上,但是当我试图得到this.element.nativeElement.getElementsByTagName('textarea')时,它总是没有定义,所以我不能按程序设置高度。

代码语言:javascript
复制
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中的工作示例。

谢谢罗维

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-22 10:20:55

代码下面的会帮助您解决问题.

代码语言:javascript
复制
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上确认了这一点。

致以问候。

票数 4
EN

Stack Overflow用户

发布于 2019-05-22 10:34:09

这个包为我做了我的离子文本区域的所有自动调整( https://github.com/chrum/ngx-autosize ),只需遵循指南并让它工作,如果它不能将它导入到app.module.ts中,然后尝试将它导入到页面的模块中,如果您愿意的话,我个人需要它,但是包是一个生命保护程序。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54174031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档