Created
June 16, 2017 12:16
-
-
Save sg6/c9a7806512da08e4122355be0002f2c4 to your computer and use it in GitHub Desktop.
Copy Content fetched from Web Service to Clipboard with Ctrl + C in Angular 2+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { MyService } from './my.service'; | |
// Adapt code to your needs, it's just a component's bootstrap | |
@Component({ | |
selector: 'app-copy', | |
template: ` | |
<div class="container" (keyup)="onKeyUp($event)" (keydown)="onKeyDown($event)" tabindex="1"> | |
<div>...some data... (click me and press ctrl + c)</div> | |
<input id="selectedDatasetInput" type="text" [(ngModel)]="activeData"> | |
</div> | |
`, | |
providers: [MyService] | |
}) | |
export class CopyComponent implements OnInit { | |
// Define lastKeyPress and activeData | |
lastKeyPress : String; | |
// activeData defines the current data which will be copied into clipboard | |
activeData : String = ""; | |
// inject your service which handles the AJAX request | |
constructor(private _myService: MyService) { } | |
ngOnInit() {} | |
// when pressing Ctrl + C, the web service is called and the needed data is saved into activeData variable | |
// Ctrl will be saved into lastKeyPress variable, and C in $event.key | |
// Some browsers have difficulties to identify which key was pressed first, so C + Ctrl is also possible in this case | |
onKeyDown($event) : void { | |
if((this.lastKeyPress === "c" && $event.key === "Control") || (this.lastKeyPress === "Control" && $event.key === "c")) { | |
this._myService.getData() | |
.subscribe(data => { | |
this.activeData = data; | |
}); | |
} | |
this.lastKeyPress = $event.key; | |
} | |
// when releasing Ctrl + C, it's the same game as before | |
// in this case, the activeData will be selected because it's bound to the input field | |
// after it's selected, it's copied with the execCommand function | |
onKeyUp($event) : void { | |
if((this.lastKeyPress === "c" && $event.key === "Control") || (this.lastKeyPress === "Control" && $event.key === "c")) { | |
document.querySelector('input').select(); | |
document.execCommand('copy'); | |
console.log('copied'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment