Copy website controls data into Clipboard using Angular (v6)

You may have came across a requirement where you wanted to provide a feature “Copy to Clipboard” on your website.

There is a library called Clipboardjs. In this story we will see how to use it with Angular (v6).

  1. Link clipboard library from CDN inside index.html.
<script src=""></script>

Alternatively you can use npm install clipboard --save

2. Let’s say you have a <input> box in app.component.html and you want to copy it’s content to clipboard on a button click. First give an id or any CSS selector to <input> and provide an attribute data-clipboard-target="#targetID" to a button.

<input id="username" type="text" value="Balram Chavan"><button id="btnCopy" data-clipboard-target="#username">Copy to Clipboard</button>

3. Open app.component.ts file. Declare clipboard js variable

declare var ClipboardJS:any;

4. Create a new object of ClipboardJS by passing a CSS selector as a constructor parameter. Here any valid CSS selector can be passed but be sure more generic selector you pass, slower application would be.

new ClipboardJS('#btnCopy');

5. Run the application using ng serve --open

And that’s it! Enter something in text box and click on a button. Open any text editor and paste the content. You should see copied text from <input> box.

You can perform cut operation as well by setting data-clipboard-action="cut" attribute on <button>.

You can also set in memory data as content to be copied rather than having some input control. Set data-clipboard-text="some data to be copied..." attribute on a button and it will get copied.




Cloud Solution Architect | Author | Full Stack Developer | |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store