如何在我打字时垂直自动调整离子输入字段的大小 [英] How to autoresize the ion-input field vertically while I am typing
问题描述
当我输入长文本时,ion-input
字段保持在相同的高度,我只能在可用的可见区域中看到文本.在我键入时,我希望输入字段根据其中的数据自动垂直调整为 2 行或 3 行.
When I am typing long text, the ion-input
field stays at the same height and I can only see the text in the available visible area. As I type, I want the input field to auto-resize vertically to 2 lines or 3 lines according to the data in it.
我的page.html
代码:
<ion-item>
<ion-input placeholder="type message here"></ion-input>
</ion-item>
我附上一个屏幕截图以澄清我要解释的内容:
I am attaching a screenshot to clarify what I am trying to explain:
推荐答案
基于 这个惊人的 repo您可以创建一个自定义指令来为您处理.
Based on this amazing repo you can create a custom directive to handle that for you.
就像您在这个工作中的 Stackblitz 项目中看到的那样,该指令如下所示:
Just like you can see in this working Stackblitz project, that directive would look like this:
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';
}
}
就是这样!为了查看它的实际效果,您可以在任何页面中使用它,如下所示:
And that's it! In order to see it in action, you can use it in any page like this:
组件
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>
这篇关于如何在我打字时垂直自动调整离子输入字段的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!