Tim Deschryver

Use the new Angular Clipboard CDK to interact with the clipboard


The helium-barbell (v9.0.0-next.1) release brings us a new CDK clipboard module to interact with the clipboard. In this post, we'll explore how to use the new CDK with some examples.

The Component Dev Kit (CDK) is a set of tools that implement common interaction patterns whilst being unopinionated about their presentation. It represents an abstraction of the core functionalities found in the Angular Material library, without any styling specific to Material Design. Think of the CDK as a blank state of well-tested functionality upon which you can develop your own bespoke components.

Import the ClipboardModule

The first step to use the CDK is to import the ClipboardModule from @angular/cdk/clipboard and add it to the imports declaration.

Using the cdkCopyToClipboard attribute

After the ClipboardModule is imported, we're good to go. The only thing needed to copy content is the cdkCopyToClipboard attribute. It's possible to add it to any element, and when the element is clicked it will save the content to your clipboard.

Copying a static string is boring, but we can also use a property binding to copy the result of an expression.

Even more fun is to bind it to a function where we can modify the content.

Using the Clipboard service

Using the cdkCopyToClipboard attribute is great to give users the possibility to copy content from a page. But it doesn't allow us, as developers, to copy content programmatically. This is where the Clipboard service comes into play. By using the copy(content) method we can copy content to the clipboard.


Implementation details

Internally, the PendingCopy is used to copy content to the clipboard. This class creates an invisible textarea in the DOM with the content as its value. When the copy() method is used, it will move the focus to the invisible textarea and use the native execCommand('copy') to copy the content to the clipboard. As the last step, it will re-focus the previously selected element.

For the ones interested, the native Clipboard API can also cut content and read the current clipboard value.

Incoming links

Please consider supporting me if have you enjoyed this post and found it useful:

Buy Me A Coffee PayPal logo
Support the blog Share on Twitter Discuss on Twitter Edit on GitHub