添加指令以自动调整ion-textarea时出错

时间:2018-01-30 09:50:02

标签: angular ionic-framework ionic3

我需要在离子应用中提供离子 - textarea。我面临的问题是我无法增加textarea的高度。搜索后,我找到了一个解决方案,通过从这个链接创建一个指令来自动调整textarea的大小: https://stackoverflow.com/a/40850483/8231819

但我收到的错误如下:

enter image description here

我的指令代码:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
selector: "ion-textarea[autoresize]" // Attribute selector
})
export class Autoresize {
  @HostListener("input", ["$event.target"])
  onInput(textArea: HTMLTextAreaElement): void {
    this.adjust();
  }

  constructor(public element: ElementRef) {
  }

  ngOnInit(): void {
    this.adjust();
  }

  adjust(): void {
    let ta = this.element.nativeElement.querySelector("textarea");
    ta.style.overflow = "hidden";
    ta.style.height = "auto";
    ta.style.height = ta.scrollHeight + "px";
  }
}

我的HTML是:

  <ion-textarea autoresize [(ngModel)]="description"></ion-textarea>

app.module.ts:

import { Autoresize } from '../directives/autosize/autosize';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    Autoresize
  ],
  imports: [
    BrowserModule,
    IonicStorageModule.forRoot(),
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
  ],
  providers: [
    StatusBar,
    Autoresize,
    {provide: ErrorHandler,useClass: IonicErrorHandler},
    Auth,
    ApiServiceProvider,
  ]
})
export class AppModule {}

更新

我在adjust函数

中添加了以下代码
console.log(this.element.nativeElement); 
console.log(this.element.nativeElement.querySelector("textar‌​ea"));

现在日志是:第一个是打印,第二个是空!

enter image description here

1 个答案:

答案 0 :(得分:1)

修改你的adjust方法如下,它将起作用:)

&#13;
&#13;
adjust(): void {
    let ta = this.element.nativeElement.querySelector("textarea");
    if (ta) {
      ta.style.overflow = "hidden";
      ta.style.height = "auto";
      ta.style.height = ta.scrollHeight + "px";
    }
  }
&#13;
&#13;
&#13;