在Ionic2中输入文本的插入符号处插入文本

时间:2016-05-30 12:35:03

标签: javascript typescript ionic2

我试图创建简单的计算器应用程序。

我想在点击(点击)按钮的输入文字的插入处插入文本。 以下代码在strPos = inputText.selectionStart;处不起作用。 似乎没有错误发生,只需停在这里。

有谁知道如何解决这个问题?

修改

page1.html

<ion-input #myInput type="text" [value]="fomula" (focus)="onFocus($event)"></ion-input>
<button class="button" id="number" (click)="numberTapped(myInput, 1)">1</button>

page1.ts

onFocus($event){
  this.currentInput = document.activeElement;
}

numberTapped($event, number) {
  this.insertAtCaret($event, String(number))
}

insertAtCaret(inputId,text) {
  var inputText:any = myInput; //document.getElementById(inputId);
  var strPos = 0;
  strPos = inputText.selectionStart;

  var front = (inputText.value).substring(0,strPos);  
  var back = (inputText.value).substring(strPos,inputText.value.length); 
  inputText.value=front+text+back;
  strPos = strPos + text.length;
  inputText.selectionStart = strPos;
  inputText.selectionEnd = strPos;
  inputText.focus();
}

2 个答案:

答案 0 :(得分:0)

调用numberTapped时,焦点已经丢失,并再次调用onFocus。所以在执行numberTapped时,this.currentInput不再是输入。

即使我认为你的方法不是最好的,但解决方案可能是

<ion-input #myinput type="text" [value]="fomula" (focus)="onFocus($event)"></ion-input>
<button class="button" id="number" (click)="numberTapped(myinput, 1)">1</button>

这样做,#myinput现在是对元素的引用。

来自文档Template Syntax

<!-- phone refers to the input element; pass its `value` to an event handler -->
<input #phone placeholder="phone number">
<button (click)="callPhone(phone.value)">Call</button>

<!-- fax refers to the input element; pass its `value` to an event handler -->
<input ref-fax placeholder="fax number">
<button (click)="callFax(fax.value)">Fax</button>
  

&#34;电话&#34;的哈希(#)前缀意味着我们正在定义手机变量。

答案 1 :(得分:0)

我在My Ionic 4项目中使用此

<ion-input #ioninput clear-input="true" placeholder="Text ..."> </ion-input>
<ion-button ion-button block (click)="insertAtCursor('value')">Button</ion-button>

Am使用Angular 8 |角度8中的ViewChild需要2个参数

import { ViewChild } from '@angular/core';
import { IonInput } from '@ionic/angular';
export class TextPage implements OnInit {
 @ViewChild('ioninput', {static: false}) ioninputRef: IonInput;
constructor(){}
 insertAtCursor(textToInsert) {
// make sure we have focus in the right input
this.ioninputRef.setFocus();
// and just run the command
document.execCommand('insertText', false /*no UI*/, textToInsert);
     }
}

希望这将对某人有所帮助:)

相关问题