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.
The first step to use the CDK is to import the
@angular/cdk/clipboard and add it to the
ClipboardModule is imported, we're good to go.
The only thing needed to copy content is the
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.
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.
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.
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.