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).
- Link clipboard library from CDN inside
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>
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.
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
You can perform
cut operation as well by setting
data-clipboard-action="cut" attribute on
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.
ng-clipboardjs - Copy data to clipboard using Angular and Clipboard.js