Create Reusable Copy-To-Clipboard Directive in Angular

Netanel Basal
Netanel Basal
Published in
1 min readJun 9, 2022

--

Including a copy button in an application is a common feature that enhances user experience, especially on mobile devices where users may have difficulty selecting text.

Let’s create a directive that simplifies our work. Our API will look like this:

As a first step, let’s create a directive and register a click handler for our host element:

In this case, I don’t use HostListener since I want to run the event outside the Angular zone to avoid triggering a redundant change detection cycle whenever a user copies data:

Now I can use the native Clipboard.writeText() API, which is supported by all major browsers, to copy the text provided by the input, and show a success message:

Note that this API works on localhost or HTTPS. If you need a fallback, you can use the deprecated execCommand API.

Let’s test our directive with Spectator:

I’m using spyOn directly on the object, but you can provide it via DI and mock it.

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.