typescript 50 lines · 9 steps

A copy-to-clipboard directive in Angular

A standalone Angular directive that copies text on click and reflects a temporary 'copied' state through host bindings.

Explained by highlit
1import { Directive, ElementRef, HostBinding, HostListener, Input, inject, signal } from '@angular/core';
2 
3@Directive({
4 selector: '[appCopyToClipboard]',
5 standalone: true,
6})
7export class CopyToClipboardDirective {
8 private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
9 
10 @Input('appCopyToClipboard') value = '';
11 @Input() resetDelay = 1500;
12 
13 private readonly copied = signal(false);
14 private timer?: ReturnType<typeof setTimeout>;
15 
16 @HostBinding('class.is-copied')
17 get isCopied(): boolean {
18 return this.copied();
19 }
20 
21 @HostBinding('attr.aria-label')
22 get label(): string {
23 return this.copied() ? 'Copied to clipboard' : 'Copy to clipboard';
24 }
25 
26 @HostListener('click')
27 async onClick(): Promise<void> {
28 const text = this.value || this.host.nativeElement.innerText.trim();
29 if (!text) return;
30 
31 try {
32 await navigator.clipboard.writeText(text);
33 this.flagSuccess();
34 } catch {
35 const range = document.createRange();
36 range.selectNodeContents(this.host.nativeElement);
37 const selection = window.getSelection();
38 selection?.removeAllRanges();
39 selection?.addRange(range);
40 if (document.execCommand('copy')) this.flagSuccess();
41 selection?.removeAllRanges();
42 }
43 }
44 
45 private flagSuccess(): void {
46 clearTimeout(this.timer);
47 this.copied.set(true);
48 this.timer = setTimeout(() => this.copied.set(false), this.resetDelay);
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Attribute directives can encapsulate behavior and DOM feedback so any element becomes copyable with a single attribute.
  2. 2Host bindings driven by a signal keep CSS classes and ARIA attributes in sync with internal state automatically.
  3. 3Wrapping a modern API like the Clipboard API in a try/catch lets you fall back to legacy techniques when it's unavailable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A copy-to-clipboard directive in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code