@angular/cdk/clipboard package provides utilities for copying text to the user’s clipboard.
Installation
Basic Usage
Clipboard Service
CdkCopyToClipboard Directive
The simplest way to copy text is using the directive:Advanced Usage
Copying from Input Elements
Copy with Feedback
Copy Code Blocks
Large Text / Pending Copy
For large strings that may take time to process:API Reference
Clipboard Service
Injectable:{providedIn: 'root'}
| Method | Returns | Description |
|---|---|---|
copy(text: string) | boolean | Copies text to clipboard, returns success |
beginCopy(text: string) | PendingCopy | Creates a pending copy for large strings |
PendingCopy
| Method | Returns | Description |
|---|---|---|
copy() | boolean | Executes the copy operation |
destroy() | void | Cleans up resources |
CdkCopyToClipboard Directive
Selector:[cdkCopyToClipboard]
| Input | Type | Description |
|---|---|---|
cdkCopyToClipboard | string | Text to copy to clipboard |
cdkCopyToClipboardAttempts | number | Number of copy attempts (default: 1) |
| Output | Type | Description |
|---|---|---|
cdkCopyToClipboardCopied | boolean | Emits whether copy succeeded |
Browser Support
The clipboard API uses the modern Clipboard API when available, falling back todocument.execCommand('copy') for older browsers.
Permissions
Some browsers require user interaction (e.g., click event) to allow clipboard access.Testing
Mocking in Tests
Accessibility
Provide feedback when copying:Best Practices
- Provide feedback - Always show success/failure to users
- Use ARIA announcements - Inform screen reader users
- Handle errors - Check return value and handle failures
- User interaction - Ensure copy is triggered by user action
- Clear messaging - Tell users what’s being copied