<input type="text" value="User input Text to copy" #userinput>
<button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>
.ts文件
/* To copy Text from Textbox */
copyInputMessage(inputElement){
inputElement.select();
document.execCommand('copy');
inputElement.setSelectionRange(0, 0);
}
import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {
@Input("copy-clipboard")
public payload: string;
@Output("copied")
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener("click", ["$event"])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload)
return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window["clipboardData"];
clipboard.setData("text", this.payload.toString());
e.preventDefault();
this.copied.emit(this.payload);
};
document.addEventListener("copy", listener, false)
document.execCommand("copy");
document.removeEventListener("copy", listener, false);
}
}
然后像这样使用它
<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
<i class="fa fa-clipboard"></i>
Copy
</a>
public notify(payload: string) {
// Might want to notify the user that something has been pushed to the clipboard
console.info(`'${payload}' has been copied to clipboard`);
}