我有一个自定义指令来调整离子文本区域的高度,使其在输入文本时自动调整高度,而不是设置固定的行高,或者在文本区域填充时设置难看的滚动条。
在Ionic-4中,我无法获得离子文本区域的html文本区域的nativeElement。任何帮助都是很好的
它运行在角度6和离子4上,但是当我试图得到this.element.nativeElement.getElementsByTagName('textarea')时,它总是没有定义,所以我不能按程序设置高度。
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中的工作示例。
谢谢罗维
发布于 2019-02-22 10:20:55
代码下面的会帮助您解决问题.
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上确认了这一点。
致以问候。
发布于 2019-05-22 10:34:09
这个包为我做了我的离子文本区域的所有自动调整( https://github.com/chrum/ngx-autosize ),只需遵循指南并让它工作,如果它不能将它导入到app.module.ts中,然后尝试将它导入到页面的模块中,如果您愿意的话,我个人需要它,但是包是一个生命保护程序。
https://stackoverflow.com/questions/54174031
复制相似问题