Angular 如何在我打字时自动调整离子输入字段的垂直大小

Angular 如何在我打字时自动调整离子输入字段的垂直大小,angular,typescript,ionic2,ionic3,Angular,Typescript,Ionic2,Ionic3,当我输入长文本时,离子输入字段保持在相同的高度,我只能在可用的可见区域看到文本。键入时,我希望输入字段根据其中的数据自动垂直调整为2行或3行 我的page.htmlcode: <ion-item> <ion-input placeholder="type message here"></ion-input> </ion-item> 我附上一张截图,以澄清我试图解释的内容: 基于您可以创建一个自定义指令来处理该问题 正如您在中看

当我输入长文本时,
离子输入
字段保持在相同的高度,我只能在可用的可见区域看到文本。键入时,我希望输入字段根据其中的数据自动垂直调整为2行或3行

我的
page.html
code:

  <ion-item>
    <ion-input placeholder="type message here"></ion-input>
  </ion-item>

我附上一张截图,以澄清我试图解释的内容:

基于您可以创建一个自定义指令来处理该问题

正如您在中看到的,该指令如下所示:

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

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class Autosize implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}
就这样!为了查看它的运行情况,您可以在如下任何页面中使用它:

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

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class Autosize implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}
组件

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  dummyText: string = `Type a longer text to see how this expands!`;

  constructor(public navCtrl: NavController) { }

}
查看

<ion-header>
  <ion-navbar>
    <ion-title>Autosizing Textarea</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <!-- Use rows="1" to initialize it as a single line text-area -->
    <ion-textarea rows="1" name="dummyText" [(ngModel)]="dummyText" autosize></ion-textarea>
  </ion-item>
</ion-content>

自动调整文本区域大小

您可以使用ion textarea组件

为什么不改为使用
,似乎符合预期目的…目的是在聊天窗口上使用,如果文本更多,字段会扩展,默认情况下我不需要扩展字段..希望我的答案能解决您的问题我能理解。我想你可以试一下
输入
,但是由于
输入
天生就不是多行的,老实说,我想你会更幸运地使用
文本区域
。这看起来不错,但我需要一个调整,因为我在blitz中键入,文本框正在向下扩展单词,我希望它向上扩展。。。你能修改一下吗现在请看一下Stackblitz项目。。。我想,只要把
文本区域
放在
离子页脚
中,你就可以实现这一点。对于离子3,记住要将
自动调整大小
添加到页面的模块中。ts
声明
部分可悲的是,通过点击一个单词来选择文本,然后用光标跳转到该位置似乎不起作用。(ionic3/android)