0

I am using mulitple textarea with autosize using ionic3 and angular, But it is working only for single textarea. Can I get a guideline to resolve this issue.Below lines are my code

home.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>

Home.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";
 }
}
Pradnya Sinalkar
  • 1,116
  • 4
  • 12
  • 26
MaryAnn
  • 393
  • 7
  • 17

1 Answers1

2

It's only working for a single text area because you told it to just run on the first one in the array

let textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];

getElementsByTagName returns an array of all the textareas on the screen. So you should try iterating over those. Something similar to:

const textAreas = this.element.nativeElement.getElementsByTagName('textarea');
textAreas.forEach(textArea => {
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + "px";
});

As a side note, you may want to look into using ViewChild/ViewChildren in the future. It is the correct way to work with/access dom elements directly in angular, and should be used when possible

I spun up a quick example using ViewChildren here Using the angular docs for ViewChildren and another stackoverflow post

canpan14
  • 1,181
  • 1
  • 14
  • 36
  • Thank you for your answer, I tried with this.element.nativeElement.getElementsByTagName('textarea');, but still having the issue. – MaryAnn Jun 30 '18 at 09:47
  • @MaryAnn I added an example of using ViewChildren to the answer, you really should be using it. Without seeing your changed code I'm not sure what the current problem is. Did you log what that code returned to make sure you are getting an array of items back? Also did you make sure to loop over that array? – canpan14 Jun 30 '18 at 16:57