Add content to the current position of the text input field in Ionic 2 by placing

I'm currently developing a simple calculator app and I'm facing an issue.

My goal is to add text at the caret position of an input text field when a button is clicked. However, the code snippet provided below is not functioning as expected:

At the line

strPos = inputText.selectionStart;
, the code seems to stop working without any errors being thrown. Is there anyone who can suggest a solution for this?

Edit

Here is a snippet from my page1.html file:

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

And here is a portion of my page1.ts file:

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();
}

Answer №1

when numberTapped is called, the focus is already lost and onFocus was called again. so at the time when numberTapped is executed, this.currentInput is not the input anymore.

while I may have reservations about your method, a potential solution could be

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

by doing this, #myinput now acts as a reference to the element.

extracted from the documentation 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>

The hash (#) prefix to "phone" signifies that we are declaring a phone variable.

Answer №2

Utilizing Ionic 4 in My Current Project

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

Currently Employing Angular 8 | Utilizing ViewChild with Two Arguments

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);
     }
}

Sharing this for anyone who might find it helpful :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to verify if the inner <div> contains any text

I am attempting to determine if the inner <div> contains the text "Ended" and then remove it if it does. There are multiple <div> elements with the same class. I have attempted to use the .filter() method. My goal is to remove the container_one ...

Validation error occurs in the jQuery form

I've been working on creating a basic form with validation, but for some reason the validation isn't working as expected. I've checked all my tags to make sure they match up, but something seems off with the closing tags at the end of the fo ...

Unable to locate npm module called stream

For some reason, our tests have stopped running since yesterday. The error message reads: module stream not found Upon investigation, we discovered that 'stream' is available as a core node module: https://nodejs.org/api/stream.html#apicontent ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

Adding picture to table using JavaScript

I am currently developing a Web application using the Play Framework technology. In one of my scala.html views, I have successfully displayed an image with the following code: <img src="@routes.Assets.at("images/image/1003.png")" width="30" height="30" ...

ASP.Net is experiencing connectivity issues with $ajax

I'm currently troubleshooting my solution on localhost and I've noticed that this particular piece of code is not communicating with the server var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html(); var dataString = ...

Merge a pair of filter conditions for an array of objects

In my React Redux application, I am working with an array of objects that are being displayed in a list. Users have the option to filter the list using a dropdown menu for names and two toggle buttons for kinds. <Table data={ array .filter( ...

javascript context scope

As I delve into the world of JavaScript, please bear with me as I navigate through defining multiple namespaces. Here's an example of how I'm doing it: var name_Class = function(){ this.variable_name_1 = {} this.method_name_1 = function() { ...

What is the best way to find the product of each object in an array by the corresponding values in another array?

Searching for a solution to an issue I encountered while working on an assignment. The problem can be illustrated as follows: var arrOfObj = [{a:10 },{a:20},{a:30}, ......] var arrToMultiply = [2,4,6, .....] The expected result const result = [{a:10,resul ...

Exploring Angular 7: Leveraging class inheritance and the powerful httpClient

It has come to my attention that my services are quite repetitive. In an attempt to enhance them, I decided to delve into super classes and inheritance in Angular. However, I have been struggling with the constructor and super calls. Despite TypeScript com ...

[REQUIRED_RESOURCE_TYPE]: The requested resource should be a string, Buffer, or an acceptable file stream

I'm attempting to apply a grayscale effect to pictures, but whenever I run the command, it shows me the error above... Any solutions? The Code : const jimp = require('jimp') const {MessageAttachment} = require('discord.js') modul ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

Uh-oh! You can't configure Next.js using 'next.config.ts'. You'll need to switch it out for 'next.config.js'

I've encountered an issue while working on my TypeScript project with Next.js. Initially, I named my config file as next.config.js, but it resulted in a warning in the tsconfig.json file stating "next.config.ts not found," leading to a warning sign on ...

What is the best way to create a custom isEmpty function that communicates to the TypeScript compiler that a false result indicates the parameter is actually defined?

I have written the following code snippet: export function myIsEmpty(input?: unknown): boolean { if (input === undefined || input === null) { return true; } if (input instanceof Array) { return input.length === 0; } return input == false; ...

What is the best way to declare and initialize a global variable in a TypeScript Node application?

When using Webpack: const WebpackConfig = { // ... plugins: [ new Webpack.DefinePlugin({ __IS_DEVELOPMENT_BUILDING_MODE__: isDevelopmentBuildingMode, __IS_TESTING_BUILDING_MODE__: isTestingBuildingMode, __IS_PRODUCTION_BUILDING_MO ...

Ways to check for child items in a JSON object

My Angular-built menu uses JSON and spans up to 3 levels deep. Some items have no children, while others go further down the hierarchy. I'm trying to determine if a selected subcategory has child elements in order to hide a button. Each time a subcat ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

Exploring async componentDidMount testing using Jest and Enzyme with React

angular:12.4.0 mocha: "8.1.2" puppeteer: 6.6.0 babel: 7.3.1 sample code: class Example extends Angular.Component<undefined,undefined>{ test:number; async componentWillMount() { this.test = 50; let jest = await import('jest&apos ...