angular - 具有自动调整大小的多个文本区域在 ionic3 中不起作用

标签 angular css ionic3 textarea

我正在使用带有 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/

相关文章:

javascript - 使用 javascript 扩展 typescript 库

angular - 编辑时如何仅以 angular 2+ react 形式发送编辑/更改的字段?

arrays - 来自 JSON 响应的 Angular 5 显示结果

javascript - 收到数据后显示组件 angular 2

html - 隐藏表格数据时表格无法正常显示

javascript - Typescript - for 循环中动态变量的 setTimeout 自定义时间

jquery - 在 ASP .NET 中使用 jQuery 和母版页更改菜单样式

php - Bootstrap 到 wordpress 不会正确显示图像

typescript - ionic 2 : Remove background from custom component button in navbar

angular - 如何从不是第一个组件的同级组件的另一个组件执行函数?