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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Attribute directives can encapsulate behavior and DOM feedback so any element becomes copyable with a single attribute.
- 2Host bindings driven by a signal keep CSS classes and ARIA attributes in sync with internal state automatically.
- 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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-copy-to-clipboard-directive-in-angular-explained-typescript-8dca/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.