"Learn the steps to seamlessly add text at the current cursor position with the angular-editor tool

How can I display the selected value from a dropdown in a text box at the current cursor position? I am currently using the following code:

enter code selectChangeHandler(event: any) {
this.selectedID = event.target.value;
// console.log("this.selectedID", this.selectedID);
this.arrayfordynamic += `<div>{{DV.Product.${this.selectedID}}}</div>`
console.log("this.arrayfordynamic", this.arrayfordynamic)
this.productDiscriptionArrayForID = `<div>${this.arrayfordynamic} </div> ${this.product.productDescription}`
// console.log("this.selectedIDwithDiscription-----", this.arrayfordynamic);
this.productForm.controls.des.setValue(this.productDiscriptionArrayForID);
}

I am currently inserting the dropdown value into an Angular Editor text. However, I would like to place this value at the cursor position when I click on a dropdown value. Can anyone provide guidance on how to achieve this?

Answer №1

Imagine you have the following input:

<input id="myInput"type="text">

To retrieve the cursor position, you can utilize this function:

function getCursor() {
  let cursor = document.getElementById('myInput');
  let start = cursor.selectionStart;
  let end = cursor.selectionEnd;
  return [start, end];
}

Next, you need to create a function to update the value:

function patchValue(selectedValue) {
  let currentValue = document.getElementById('myInput').value;
  let cursor = getCursor();
  let patchedValue = currentValue.substr(0, cursor[0]) + selectedValue + currentValue.substr(cursor[1]);
  document.getElementById('myInput').value = patchedValue;
}

You can also highlight a specific range and substitute it with a selected value using the following code snippet.

Take a look at this example:

function getCursor() {
  let cursor = document.getElementById('myInput');
  let start = cursor.selectionStart;
  let end = cursor.selectionEnd;
  return [start, end];
}

function patchValue() {
  let currentValue = document.getElementById('myInput').value;
  let cursor = getCursor();
  let patchedValue = currentValue.substr(0, cursor[0]) + document.getElementById('myPatch').value+ currentValue.substr(cursor[1]);
  document.getElementById('myInput').value = patchedValue;
}
<label>patch:</label><input id="myPatch"type="text">
<br>
<label>input:</label><input id="myInput"type="text">
<br>
<button onclick="patchValue()">patch</button>

Answer №2

Simply add the phrase "as HTMLInputElement" and everything will work perfectly.

 getCursor() {
    let cursor = document.getElementById('texto-value') as HTMLInputElement;
    let start = cursor.selectionStart;
    let end = cursor.selectionEnd;
    return [start, end];
  }

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

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...

Error in Node Redis-OM: the function generateId of this[#schema] is not recognized

Hey everyone, I'm currently facing an issue with saving an entity into a Redis repository. The driver is connected correctly, the schema and repo are set up as expected. However, when I attempt to save the entity, I encounter the following exception: ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

What are the steps to incorporate a type-safe builder using phantom types in TypeScript?

In order to ensure that the .build() method can only be called once all mandatory parameters have been filled, it is important to implement validation within the constructor. ...

Tips for troubleshooting errors when starting a new Angular project

Journey On my Windows machine, I initially had npm 6.4.1 and node 8.12.0 installed. I decided to upgrade in the following sequence: Started with upgrading npm Then moved on to upgrading node However, now when attempting to create a new app, I encounte ...

Using jQuery to set the background-image on the body's after pseudo-element with CSS

I am currently utilizing body:after for setting the page wallpaper. body:after { background-image: url('assets/img/wallpapers/<?php echo $getWallpaperFile; ?>'); } CSS content: ' '; display: block; position: absolute; left: ...

Securing NextJS API Routes with API Key Authorization

I'm developing an app in NextJS 13 that utilizes API routes, and I aim to secure them against any unauthorized access from external functions. While my app integrates Auth0, there is no strict requirement for protection since unregistered individuals ...

Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace th ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

When you click on the Admin Panel Side menu, the page refreshes instead of expanding the menu item

I have encountered a strange problem with the AdminLTE admin panel template that I am using in my Angular 11 application. Everything is loading fine with the menu items, but when I click on an item, instead of expanding the group, the page refreshes. Here ...

maintain ajax history during jquery redirection

Currently, I am designing a compact application using php, jquery, and ajax. The purpose of this app is to enable users to conduct customer searches, view customer details, and easily navigate back to the search page without losing any data. To enhance use ...

Ways to identify a modification in ag-grid when there is an update in my row data while transitioning from one component to another

I am currently working on a project using angular6 implementing ag-grid to display data from an angular dialog box. With multiple teams contributing, each creating their own components, I have encountered a unique situation that I am struggling to resolv ...

Learn the process of transferring data from a page to a layout in NUXT

I am in the process of creating a basic website. The goal is to dynamically change the Navbar elements based on the data set in the navLayout within the page template. My plan is to pass this data to the layout and then utilize props to transmit it to the ...

Align a div vertically in a responsive design layout

How can I get the text inside "grid2" and "section2" to vertically align in the middle? Is this issue related to my HTML or is it a problem with the CSS? Can someone guide me in the right direction? I have searched for similar questions but the answers h ...

What is preventing me from accessing the attribute of this particular entity? (Using Angular and MongoDB)

I am currently in the process of developing an angular application that utilizes a MongoDB database and a NodeJS server. The concept behind this application is to create a platform where users can access a list of posts along with detailed post informatio ...

The presence of a backslash is preventing the state from transitioning to '/{username:[a-zA-Z0-9]{3,20}}' within the AngularJs UI-router

In my abstract root state named 'site', the empty URL ('') contains two child states: 'profile' and 'home'. The URL for home is '/', while the URL for profile is '/{username:[a-zA-Z0-9]{3,20}}'. I ...

Adjust the image size in the jumbotron to fit perfectly without the need for scrolling

I'm in the process of creating a website with a prominent jumbotron section on the landing page. I am looking to adjust the height of the image within the jumbotron without cutting off any parts of the picture, and I do not want it to scroll to displa ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...