gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:07:49 29 4
gpt4 key购买 nike

我有一个自定义指令来调整 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com