我正在使用带有 ionic3 和 angular 自动调整大小的多文本区域,但它仅适用于单个文本区域。我能得到解决这个问题的指南吗?下面几行是我的代码
主页.html
<ion-list [formGroup]="editForm">
<ion-item>
<ion-label floating class="label">Description1</ion-label>
<ion-textarea autosize formControlName="desc"></ion-textarea>
</ion-item>
<ion-item>
<ion-label floating class="label">Description2</ion-label>
<ion-textarea autosize formControlName="desce"></ion-textarea>
</ion-item>
</ion-list>
主页.ts
import { Component, Directive, OnInit, HostListener, ElementRef } from '@angular/core';
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html',
})
@Directive({
selector: 'ion-textarea[autosize]'
})
export class Home implements OnInit {
@HostListener('input', ['$event.target'])
onInput(textArea: HTMLTextAreaElement): void {
this.adjust();
}
constructor(public element: ElementRef,){}
ngOnInit(): void {
setTimeout(() => this.adjust(), 0);
}
adjust(): void {
let textArea =
this.element.nativeElement.getElementsByTagName('textarea')[0];
textArea.style.overflow = 'hidden';
textArea.style.height = 'auto';
textArea.style.height = textArea.scrollHeight + "px";
}
}
最佳答案
它只适用于单个文本区域,因为您告诉它只在数组中的第一个文本区域上运行
let textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
getElementsByTagName 返回屏幕上所有文本区域的数组。所以你应该尝试迭代那些。类似于:
const textAreas = this.element.nativeElement.getElementsByTagName('textarea');
textAreas.forEach(textArea => {
textArea.style.overflow = 'hidden';
textArea.style.height = 'auto';
textArea.style.height = textArea.scrollHeight + "px";
});
作为旁注,您可能希望在将来研究使用 ViewChild/ViewChildren。这是直接在 Angular 中使用/访问 dom 元素的正确方法,应尽可能使用
I spun up a quick example using ViewChildren here 使用 ViewChildren 的 Angular 文档和另一个 stackoverflow post
关于angular - 具有自动调整大小的多个文本区域在 ionic3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100971/