|
| 1 | +**Warning: this service is still experimental. It may have bugs and the API may change at any |
| 2 | +time** |
| 3 | + |
| 4 | +The clipboard package provides helpers for working with the system clipboard. |
| 5 | + |
| 6 | +## `Clipboard` service |
| 7 | + |
| 8 | +The `Clipboard` service copies text to the |
| 9 | +user's clipboard. It has two methods: `copy` and `beginCopy`. For cases where |
| 10 | +you are copying a relatively small amount of text, you can call `copy` directly |
| 11 | +to place it on the clipboard. |
| 12 | + |
| 13 | +```typescript |
| 14 | +class HeroProfile { |
| 15 | + constructor(private clipboard: Clipboard) {} |
| 16 | + |
| 17 | + copyHeroName() { |
| 18 | + this.clipboard.copy('Alphonso'); |
| 19 | + } |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +However, for longer text the browser needs time to fill an intermediate |
| 24 | +textarea element and copy the content. Directly calling `copy` may fail |
| 25 | +in this case, so you can pre-load the text by calling `beginCopy`. This method |
| 26 | +returns a `PendingCopy` object that has a `copy` method to finish copying the |
| 27 | +text that was buffered. Please note, if you call `beginCopy`, you must |
| 28 | +clean up the `PendingCopy` object by calling `destroy` on it after you are |
| 29 | +finished. |
| 30 | + |
| 31 | +```typescript |
| 32 | +class HeroProfile { |
| 33 | + lifetimeAchievements: string; |
| 34 | + |
| 35 | + constructor(private clipboard: Clipboard) {} |
| 36 | + |
| 37 | + copyAchievements() { |
| 38 | + const pending = this.clipboard.beginCopy(this.lifetimeAchievements); |
| 39 | + let remainingAttempts = 3; |
| 40 | + const attempt = () => { |
| 41 | + const result = pending.copy(); |
| 42 | + if (!result && --remainingAttempts) { |
| 43 | + setTimeout(attempt); |
| 44 | + } else { |
| 45 | + // Remember to destroy when you're done! |
| 46 | + pending.destroy(); |
| 47 | + } |
| 48 | + } |
| 49 | + setTimeout(attempt); |
| 50 | + } |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +## `cdkCopyToClipboard` directive |
| 55 | + |
| 56 | +The `cdkCopyToClipboard` directive can be used to easily add copy-on-click |
| 57 | +functionality to an existing element. The directive selector doubles as an |
| 58 | +`@Input()` for the text to be copied. |
| 59 | + |
| 60 | +```html |
| 61 | +<img src="avatar.jpg" alt="Hero avatar" [cdkCopyToClipboard]="getShortBio()"> |
| 62 | +``` |
0 commit comments