Skip to content
This repository was archived by the owner on Oct 7, 2020. It is now read-only.

Commit a9a502e

Browse files
benjaminforrastrimox
authored andcommitted
demos: Add copy to clipboard button (#1895)
closes #1782
1 parent 55210c6 commit a9a502e

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

demos/src/app/shared/example-viewer/example-viewer.html

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,9 @@
77
<mdc-tab *ngFor="let tab of tabs" [label]="tab.label"></mdc-tab>
88
</mdc-tab-scroller>
99
</mdc-tab-bar>
10-
<pre><code [highlight]="currentExample" *ngIf="open"></code></pre>
10+
<div class="example-container" *ngIf="open">
11+
<button mdcIconButton class="example-copy-button" (click)="copyCode()">
12+
<mdc-icon>file_copy</mdc-icon>
13+
</button>
14+
<pre><code [highlight]="currentExample"></code></pre>
15+
</div>

demos/src/app/shared/example-viewer/example-viewer.scss

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,14 @@
77
margin-top: 20px;
88
background-color: #344955 !important;
99
}
10+
11+
.example-container {
12+
position: relative;
13+
}
14+
15+
.example-copy-button {
16+
position: absolute;
17+
right: 0;
18+
top: 0;
19+
color: #ffffff;
20+
}

demos/src/app/shared/example-viewer/example-viewer.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { Component, Input, OnInit, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
1+
import {ChangeDetectionStrategy, Component, Input, OnInit, ViewEncapsulation} from '@angular/core';
22

33
import {MdcTabActivatedEvent} from '@angular-mdc/web';
4+
import {MdcSnackbar} from '@angular-mdc/web/snackbar';
45

56
interface Example {
67
label?: string;
@@ -39,11 +40,36 @@ export class ExampleViewer implements OnInit {
3940
}
4041
private _example: Example;
4142

43+
constructor(private snackbar: MdcSnackbar) {}
44+
4245
ngOnInit(): void {
4346
this.currentExample = this.tabs[0].source;
4447
}
4548

4649
onActivatedTab(event: MdcTabActivatedEvent): void {
4750
this.currentExample = this.tabs[event.index].source;
4851
}
52+
53+
copyCode(): void {
54+
const tempTextarea = document.createElement('textarea');
55+
tempTextarea.id = 'txt';
56+
tempTextarea.style.position = 'fixed';
57+
tempTextarea.style.top = '0';
58+
tempTextarea.style.left = '0';
59+
tempTextarea.style.opacity = '0';
60+
tempTextarea.value = this.currentExample;
61+
document.body.appendChild(tempTextarea);
62+
tempTextarea.select();
63+
64+
try {
65+
const returnValue = document.execCommand('copy');
66+
if (returnValue) {
67+
this.snackbar.open('Code copied');
68+
}
69+
} catch (err) {
70+
this.snackbar.open('Unable to copy.');
71+
} finally {
72+
document.body.removeChild(tempTextarea);
73+
}
74+
}
4975
}

0 commit comments

Comments
 (0)