数据绑定后更改样式

时间:2019-04-03 18:46:47

标签: angular

我试图在数据绑定后更改ion-textarea的CSS样式,但找不到正确的方法。

html文件

<ion-textarea id='headline' placeholder='{{ "CREATE.TITLE" | translate 
     }}' [(ngModel)]='contentTitle' 
          (input)="autoSizeDescription($event);"></ion-textarea>

ts文件

var elems = document.getElementsByTagName("ion-textarea");
for (var i = 0 ; i < elems.length ; i ++) {
  var textArea: any = <HTMLElement>elems[i];
  textArea.style.overflow = 'hidden';
  textArea.style.height     = 'auto';
  textArea.style.height     = textArea.scrollHeight + 'px';
}

通过数据绑定,textArea包含了一些文本,我需要调整textarea的大小以显示全文。 当我在textarea上添加一些文本时,此代码有效,但是我需要在初始步骤中显示全文。 反正有解决这个问题的方法吗? 预先感谢。

1 个答案:

答案 0 :(得分:0)

我正在使用Ionic 4

使用 @ViewChildren @ViewChild (如果只有一个输入元素)和 ionViewDidEnter

首先在 ion-textarea 元素上使用 #growingTextArea 更新您的html。您应该能够按名称定位元素,但这对我不起作用。

 <ion-textarea 
    #growingTextArea 
    id='headline' 
    placeholder='{{ "CREATE.TITLE" | translate }}' 
    [(ngModel)]='contentTitle'
    (input)="autoSizeDescription($event);">
  </ion-textarea>

然后

export class App {
    @ViewChildren("growingTextArea") ionTextAreas: QueryList<TextInput>
    // ..or
    @ViewChild("headline") headlineTextArea: TextInput

    ionViewDidEnter() {
      this.ionTextAreas.forEach(textArea => {
        //debugger;
        this.adjustTextBox(textArea._native.nativeElement);
      });
    }

    autoSizeDescription(event: any): void {
       this.adjustTextBox(event.target);
       return;
    }

    private adjustTextBox(target: any) {
       target.style.overflow = 'hidden';
       target.style.height = 'auto';
       target.style.height = target.scrollHeight + 'px';
    }
 }

如果您使用的是Ionic的较新版本,则可能需要在 ionViewDidEnter()中选择本机文本区域元素来调整代码。这行-> textArea._native.nativeElement 。只需在 ionViewDidEnter 中的foreach循环中添加 debugger; 行,然后检查该元素以查找如何获取本机textarea元素。 https://ionicframework.com/docs/api/textarea#methods

参考文献:

https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

https://alligator.io/angular/viewchild-access-component/

相关问题