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 { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
typescript
import { CanActivate, ExecutionContext, Injectable,
Role-based access with a NestJS guard
authorization
guards
decorators
Intermediate
6 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.