Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different method. Can anyone spot what's wrong with my code?

HTML:

<p>
  <span
    id="sticker"
    contenteditable
    [textContent]="_stickerData?.StickerData"
    (input)="onStickerDataChange($event.target.innerHTML)"
  >
    {{_stickerData?.StickerData}}
  </span>
</p>
<button
  mat-button
  id="btnCopy"
  matRipple
  class="purple-500 fuse-white-fg mr-12"
  (click)="copyText()"
>
  Copy
</button>

TS:

copyText() {
  const sticker = document.getElementById("sticker");
  const btnCopy = document.getElementById("btnCopy");

  btnCopy.onclick = () => {
    document.querySelector("sticker");
    document.execCommand("copy");
  };
  this._messages.Show("Copied", "SUCCESS", 3);
}

Answer №1

Kindly update your code with the following:

copyText(value: string) {
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = value;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);

    this._messages.Show("Copied", "SUCCESS", 3);
}

Additionally, adjust the HTML code as shown below:

 <button mat-button id="btnCopy" matRipple class="purple-500 fuse-white-fg mr-12" (click)="copyText(_stickerData?.StickerData)">Copy</button>

I believe that these changes will suit your requirements perfectly :)

So, what exactly does this function accomplish? In a nutshell: it generates a hidden textarea, copies the specified value, and cleans up afterwards.

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

Using AngularJS with angular-google-maps to easily add markers through a form and locate your position with one click

I'm attempting to replicate the functionality demonstrated on since it fulfills 90% of my requirements. However, I'm facing some difficulties. While I can retrieve my location and log it in the console, a marker is not appearing on the map. Add ...

Is the image clickable to slide back and forth?

How can I achieve a sliding effect when clicking on the bottom-coupon class? Currently, I am only able to implement show and hide functionalities without any sliding effects. The picture slowly hiding from right to left, with the coupon-layer sliding out f ...

Using PHP to send JSONP callback responses

Is it possible to achieve "two-way" communication using JSONP and PHP? For example: jQuery / JSONP $.ajax({ url: 'http://server/po.php', cache : false, dataType: 'jsonp', timeout: 30000, type: 'GET', ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Load JavaScript files in order within the <body> tag and trigger a callback function when all files have

Currently, my website (which is actually a Cordova/Phonegap app) has the following scripts in the <head>: <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="appPolyfills.js"></script> ...

Conceal a column within a table by double-clicking

I'm working on a project with a table, and I'd like to implement a feature where a column hides when double-clicked. I've seen various solutions for hiding columns on Stack Overflow, but I could use some guidance on where to add the ondblcli ...

What is the process for clicking a button in Selenium Python that lacks a "select" tag and only becomes clickable after fulfilling certain conditions?

Currently, I am working on automating the process of downloading files. To locate these files, I need to interact with two dropdown menus: one named 'Select Period' where I choose a date, and the other named 'Select File Type' where I s ...

There are two modals present on the page, however only one of them is triggered for all actions in Angular 2

I'm encountering an issue with my page where I have set up two confirmation modals - one for resetting a form and another for deleting an item. Strangely, only the reset modal is being triggered for both actions and I can't figure out why. Could ...

Tips for incorporating additional file attachments in MVC and jQuery for uploading files

After exiting Yahoo, a new feature was introduced for attaching files. Once you click on the "Attach more files" button, it transforms into a single field where you can insert the file. The code snippet is shown below: <a href = "javascript: addUploa ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

Is there a way to determine if a user has the ability to navigate forward in Next.js?

I am faced with a challenge of determining whether a user can navigate forward on a webpage. My goal is to have two buttons - one to go back and another to go forward, with the forward button disabled when navigation is not possible. For the back button f ...

The page container does not have a specified height

I am currently working on a website with the following structure: <body> <div id="container"> <!-- all content goes here --> </div> </body> My challenge is to center the page without using float, The body has a ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

Placement of Buttons Inside a Division Tag

Is there a better way to align button 3 & 4 in a vertical column next to button 1 & 2 without using tables in CSS? See the working example below: https://jsfiddle.net/Jaron787/0te3cs66/1/ Code: HTML <div id="lse" class="display"> <di ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $req ...

Managing relationships within TypeORM's single table inheritance using a base class for targeting relations

In my application, I aim to provide users with notifications in the form of news items of various types. The relationship between User and NewsItem needs to be one-to-many, with NewsItem serving as a base class for different types of news items. Below is ...

Ways to Adjust Website Scaling for Varying Screen Sizes

Is there a way to adjust my website's scale based on the device width, such as changing it to 0.7 for certain devices? The only information I've found so far is using the <meta> tag: <meta name="viewport" content="width=device-width, i ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...