# Angular CopyButton Component

CopyButton copies a value, the result of an async function or the text of an input or a code block to the clipboard, with an optional HTML version for a rich copy. It reuses the Button styles, shows a check and announces the result, falls back to execCommand outside secure contexts and comes with a pCopyToClipboard directive for any element. It has no dependency.

## Basic

CopyButton copies its value to the clipboard when it is clicked. Its icon turns into a check and its text into "Copied" for a moment, and the result is announced to screen readers. It uses the Clipboard API in a secure context and an execCommand fallback elsewhere, so it also works on an intranet served over plain HTTP.

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';

@Component({
    template: `
        <div class="card flex flex-wrap items-center justify-center gap-4">
            <code class="px-3 py-2 rounded-border bg-surface-100 dark:bg-surface-800">npm install &#64;exhaustive-ui/core</code>
            <p-copy-button value="npm install @exhaustive-ui/core" />
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule]
})
export class CopybuttonBasicDemo {
}
```

## Button Styles

CopyButton is a Button: severity , variant ( text or outlined ), size , rounded and raised work the same way. It is secondary by default. iconOnly hides the text, which stays the accessible name of the button; add tooltip to show it on hover and focus. In text and outlined buttons, the check icon is green after a copy.

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-6">
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-copy-button value="Icon only" [iconOnly]="true" [tooltip]="true" />
                <p-copy-button value="Icon only, text" [iconOnly]="true" variant="text" [rounded]="true" [tooltip]="true" />
                <p-copy-button value="Icon only, outlined" [iconOnly]="true" variant="outlined" [tooltip]="true" />
                <p-copy-button value="With label" />
                <p-copy-button value="With label, text" variant="text" />
                <p-copy-button value="With label, outlined" variant="outlined" [rounded]="true" />
            </div>
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-copy-button value="primary" severity="primary" />
                <p-copy-button value="success" severity="success" />
                <p-copy-button value="info" severity="info" />
                <p-copy-button value="warn" severity="warn" />
                <p-copy-button value="help" severity="help" />
                <p-copy-button value="danger" severity="danger" />
                <p-copy-button value="contrast" severity="contrast" />
            </div>
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-copy-button value="small" size="small" />
                <p-copy-button value="normal" />
                <p-copy-button value="large" size="large" />
                <p-copy-button value="small" size="small" [iconOnly]="true" />
                <p-copy-button value="large" size="large" [iconOnly]="true" />
            </div>
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule]
})
export class CopybuttonStylesDemo {
}
```

## Copy from a Target

target copies the text of an element instead of a value, read at the time of the click: the value of an input, a textarea or a select, the text content of any other element such as a code block. It takes a template reference, an ElementRef or a CSS selector.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';
import { InputGroupModule } from '@exhaustive-ui/core/inputgroup';
import { InputGroupAddonModule } from '@exhaustive-ui/core/inputgroupaddon';
import { InputTextModule } from '@exhaustive-ui/core/inputtext';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-6">
            <div class="flex flex-col gap-2 w-full max-w-96">
                <label for="copybutton-target-key">API key</label>
                <p-input-group>
                    <input #apiKey id="copybutton-target-key" pInputText [(ngModel)]="key" />
                    <p-input-group-addon>
                        <p-copy-button [target]="apiKey" [iconOnly]="true" variant="text" ariaLabel="Copy the API key" [tooltip]="true" />
                    </p-input-group-addon>
                </p-input-group>
            </div>
            <div class="relative w-full max-w-[32rem]">
                <pre #codeBlock class="m-0 p-4 pr-28 rounded-border border border-surface bg-surface-50 dark:bg-surface-900 whitespace-pre-wrap break-words"><code>{{ snippet }}</code></pre>
                <p-copy-button [target]="codeBlock" size="small" class="absolute top-2 right-2" ariaLabel="Copy the code" />
            </div>
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule, InputGroupModule, InputGroupAddonModule, InputTextModule, FormsModule]
})
export class CopybuttonTargetDemo {
    key = 'sk_live_51HqLyjWDarjtT1zdp7dc';

    snippet = `import { CopyButton } from '@exhaustive-ui/core/copybutton';

@Component({
    imports: [CopyButton],
    template: \`<p-copy-button value="Hello" />\`
})
export class Example {}`;
}
```

## Async Value

value also takes a function, called on each click, that returns the text or a promise of it, for a text that is costly to build or comes from the server, such as a share link or a one-time token. While the promise is pending, the promise itself is given to the clipboard inside a ClipboardItem : Safari only accepts a write that starts during the click. A rejected promise emits copyError .

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <p-copy-button [value]="createShareLink" [labels]="{ copy: 'Copy a share link' }" severity="primary" (copied)="lastLink = $event.text" />
            @if (lastLink) {
                <span class="text-sm text-muted-color">Copied: {{ lastLink }}</span>
            }
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule]
})
export class CopybuttonAsyncDemo {
    lastLink = '';

    createShareLink = () => new Promise<string>((resolve) => setTimeout(() => resolve('https://exhaustive-ui.com/s/' + Math.random().toString(36).slice(2, 10)), 400));
}
```

## Rich Copy

html writes an HTML version next to the text, a string or a function like value . Pasted into a word processor or a mail, the content keeps its formatting, links and tables; a plain text editor receives the value . Without ClipboardItem , the fallback sets both formats in the copy event.

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <table class="text-left border-collapse">
                <thead>
                    <tr>
                        <th class="px-3 py-1 border-b border-surface">Release</th>
                        <th class="px-3 py-1 border-b border-surface">Angular</th>
                    </tr>
                </thead>
                <tbody>
                    @for (row of releases; track row.version) {
                        <tr>
                            <td class="px-3 py-1">{{ row.version }}</td>
                            <td class="px-3 py-1">{{ row.angular }}</td>
                        </tr>
                    }
                </tbody>
            </table>
            <p-copy-button [value]="text" [html]="html" [labels]="{ copy: 'Copy the table' }" variant="outlined" />
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule]
})
export class CopybuttonRichDemo {
    releases = [
        { version: '22.10', angular: '22.x' },
        { version: '21.x', angular: '21.x' }
    ];

    text = this.releases.map((row) => `${row.version}\t${row.angular}`).join('\n');

    html = `<table><tr><th>Release</th><th>Angular</th></tr>${this.releases.map((row) => `<tr><td>${row.version}</td><td>${row.angular}</td></tr>`).join('')}</table>`;
}
```

## Directive

The pCopyToClipboard directive copies on a click on any element: a Button, a link, a menu item. Its value is the text, a function or, when empty, the text of the element itself; copyTarget , copyHtml , copyFeedbackDuration , copyLabels and copyDisabled work like the inputs of the button. The result is announced to screen readers and the element has a data-p-copy-state attribute, copied or failed , during the feedback, to style it. An element that is not a button, a link or a form field gets the button role, enters the tab order and copies with Enter and Space.

```typescript
import { Component } from '@angular/core';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';
import { check, link as linkIcon } from '@exhaustive-ui/icons/round';
import { SvgIcon } from '@exhaustive-ui/core/icon';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-6">
            <button pButton type="button" pCopyToClipboard="https://exhaustive-ui.com/copybutton" #copy="pCopyToClipboard" [outlined]="true">
                <svg pIcon pButtonIcon [icon]="copy.state() === 'copied' ? check : linkIcon"></svg>
                <span pButtonLabel>{{ copy.state() === 'copied' ? 'Link copied' : 'Copy the link' }}</span>
            </button>
            <code pCopyToClipboard aria-label="Copy pnpm add &#64;exhaustive-ui/core" class="copy-chip px-3 py-2 rounded-border bg-surface-100 dark:bg-surface-800 cursor-pointer">pnpm add &#64;exhaustive-ui/core</code>
        </div>
    `,
    standalone: true,
    imports: [SvgIcon, CopyButtonModule, ButtonModule]
})
export class CopybuttonDirectiveDemo {
    check = check;
    linkIcon = linkIcon;
}
```

## Feedback and Events

feedbackDuration is how long, in milliseconds, the check icon and the "Copied" text stay, 2000 by default; 0 keeps the button as it is and only announces the result. copied gives the copied text and HTML, copyError the error when nothing could be copied, both with the original event; the button then shows a cross and "Copy failed". copy() starts a copy from your code and resolves to whether it succeeded. The icon template replaces the icons, with the state, idle , copied or failed , as context.

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';
import type { CopyButtonCopyEvent, CopyButtonErrorEvent } from '@exhaustive-ui/core/copybutton';
import { clone, thumbsUp } from '@exhaustive-ui/icons/round';
import { SvgIcon } from '@exhaustive-ui/core/icon';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-copy-button value="Short feedback" [feedbackDuration]="600" (copied)="log('copied', $event)" />
                <p-copy-button [value]="failing" severity="danger" variant="outlined" [labels]="{ copy: 'Copy (always fails)' }" (copyError)="log('copyError', $event)" />
                <p-copy-button value="Custom icon" variant="text">
                    <ng-template #icon let-state let-iconClass="class">
                        <svg pIcon [icon]="state === 'copied' ? thumbsUp : clone" [class]="iconClass"></svg>
                    </ng-template>
                </p-copy-button>
            </div>
            <ul class="m-0 p-0 list-none text-sm text-muted-color min-h-20" aria-label="Events">
                @for (entry of events; track entry.id) {
                    <li>{{ entry.text }}</li>
                }
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SvgIcon, CopyButtonModule]
})
export class CopybuttonFeedbackDemo {
    thumbsUp = thumbsUp;
    clone = clone;
    events: { id: number; text: string }[] = [];

    private id = 0;

    failing = () => Promise.reject(new Error('The server did not answer'));

    log(name: string, event: CopyButtonCopyEvent | CopyButtonErrorEvent) {
        const detail = 'text' in event ? `"${event.text}"` : String((event.error as Error)?.message ?? event.error);
        this.events = [{ id: ++this.id, text: `${name}: ${detail}` }, ...this.events].slice(0, 3);
    }
}
```

## Labels

The texts, copy , copied and failed , are shown and announced. Translate them for one button with labels , or for the whole application with the copy , copied and copyFailed keys of the aria translation. Missing keys keep their English default.

```typescript
import { Component } from '@angular/core';
import { CopyButtonModule } from '@exhaustive-ui/core/copybutton';

@Component({
    template: `
        <div class="card flex flex-wrap items-center justify-center gap-3">
            <p-copy-button value="Bonjour" [labels]="{ copy: 'Copier', copied: 'Copié', failed: 'Échec de la copie' }" />
            <p-copy-button value="Hallo" [labels]="{ copy: 'Kopieren', copied: 'Kopiert', failed: 'Kopieren fehlgeschlagen' }" />
        </div>
    `,
    standalone: true,
    imports: [CopyButtonModule]
})
export class CopybuttonLabelsDemo {
}
```

## Accessibility

Screen Reader CopyButton is a native button . Its visible text, "Copy", is its accessible name; with iconOnly , the same text becomes its aria-label . ariaLabel gives a more precise name, such as "Copy the API key"; when the text is visible, it has to contain it, so that voice control users can say what they see. The icons are hidden from assistive technologies. The result is announced by a polite live region, "Copied" or "Copy failed", without moving the focus: the button keeps it, even when the fallback has to select a hidden text area to copy. During the feedback, the visible text and the name of an icon only button become the result too. The pCopyToClipboard directive announces through the live announcer of the Angular CDK, and gives the button role and a place in the tab order to an element that has none, such as a code sample; give it an aria-label that starts with its visible text, or with "Copy" followed by it. The texts are translated with labels or the aria translation. The check and cross icons of text and outlined buttons are green and red with a 3:1 contrast or more in both color schemes, never the only sign of the result; their animation is disabled when the user prefers reduced motion.

## Copy Button

CopyButton copies a text to the clipboard: a value, a function that returns it, maybe asynchronously, or the text of a target element such as an input or a code block, optionally with an HTML version for a rich copy. The icon turns into a check for a moment and the result is announced to screen readers.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | any | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| value | CopyButtonValue | - | Text to copy, or a function called on each copy that returns it, maybe as a promise. Ignored when target is set. |
| target | CopyButtonTarget | - | Element whose text is copied when the button is clicked: an element or template reference, an ElementRef or a CSS selector. The value of an input, a textarea or a select is copied, the text content of any other element. |
| html | CopyButtonValue | - | HTML version of the text, or a function that returns it, for a rich copy: pasted into a document or a mail, it keeps its formatting, while editors of plain text receive the value. |
| feedbackDuration | number | 2000 | Duration of the visual feedback, the check icon and the copied text, in milliseconds. 0 disables it; the result is still announced. |
| iconOnly | boolean | false | Whether the button only shows the icon. Its text is then its accessible name. |
| tooltip | boolean | false | Whether a tooltip shows the text of the button on hover and focus, useful with iconOnly. |
| tooltipPosition | "top" \| "bottom" \| "left" \| "right" | 'top' | Position of the tooltip. |
| severity | ButtonSeverity | 'secondary' | Defines the style of the button, as in Button. |
| variant | "text" \| "outlined" | - | Specifies the variant of the button, as in Button. |
| size | "small" \| "large" | - | Defines the size of the button. |
| rounded | boolean | false | Add a circular border radius to the button. |
| raised | boolean | false | Add a shadow to indicate elevation. |
| disabled | boolean | false | When present, it specifies that the button should be disabled. |
| tabindex | number | - | Index of the button in the tab order. |
| autofocus | boolean | false | When present, it specifies that the button should automatically get focus on load. |
| ariaLabel | string | - | Accessible name of the button in the idle state, such as "Copy the API key". With a visible text, it has to contain that text. |
| announceResult | boolean | true | Whether the result is announced to screen readers through a polite live region. |
| labels | Partial<CopyButtonLabels> | - | Texts of the component, merged with the translation and the defaults. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| copied | event: CopyButtonCopyEvent | Callback to invoke when the text has been copied. |
| copyError | event: CopyButtonErrorEvent | Callback to invoke when the copy failed: clipboard refused, value function that threw or rejected. |

### Templates

| Name | Type | Description |
|------|------|-------------|
| icon | TemplateRef<CopyButtonIconTemplateContext> | Custom icon template. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| reset |  | void | Returns to the idle state, before the end of the feedback. |
| copy | event: Event | void | Copies the value, or the text of the target, to the clipboard. Called by a click on the button. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| host | PassThroughOption<HTMLElement, I> | Used to pass attributes to the host's DOM element. |
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element, the host. |
| pcButton | ButtonPassThrough | Used to pass attributes to the Button component. |
| tooltipTarget | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the element that holds the button and the tooltip, when tooltip is enabled. |
| tooltip | TooltipPassThrough | Used to pass attributes to the Tooltip directive. |
| icon | PassThroughOption<SVGElement, I> | Used to pass attributes to the copy, check or error icon. |
| liveRegion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the live region that announces the result. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-copybutton | Class name of the root element |
| p-copybutton-copied | Class name of the root element after a copy |
| p-copybutton-failed | Class name of the root element after a failed copy |
| p-copybutton-tooltip-target | Class name of the element that holds the button when tooltip is enabled |
| p-copybutton-button | Class name of the button element |
| p-copybutton-icon | Class name of the icon element |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| copybutton.transition.duration | --p-copybutton-transition-duration | Transition duration of root |
| copybutton.icon.size | --p-copybutton-icon-size | Size of icon |
| copybutton.icon.sm.size | --p-copybutton-icon-sm-size | Size of icon in a small button |
| copybutton.icon.lg.size | --p-copybutton-icon-lg-size | Size of icon in a large button |
| copybutton.icon.copied.color | --p-copybutton-icon-copied-color | Copied color of icon, in text and outlined buttons |
| copybutton.icon.failed.color | --p-copybutton-icon-failed-color | Failed color of icon, in text and outlined buttons |

