如何在Angular 2 Typescript中复制到剪贴板? [英] How do I copy to clipboard in Angular 2 Typescript?

查看:336
本文介绍了如何在Angular 2 Typescript中复制到剪贴板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2 Typescript框架中是否可以在剪贴板(多浏览器)中复制文本?

Is there a way to copy text in clipboard (multi-browser) in Angular2 Typescript framework?

我仅找到使用Javascript的来源,例如

I find only sources of using Javascript, e.g.

document.execCommand('copy')

推荐答案

您可以在 clipboard.js 库.

首先将库配置为SystemJS:

First configure the library into SystemJS:

<script>
  System.config({
    map: {
      clipboard: 'https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.js'
    },
    packages: {
      'app': {
        defaultExtension: 'js'
      }
    } 
  });
  (...)
</script>

我们希望能够通过指令将剪贴板附加到元素上,并提供要链接的DOM元素作为参数.在指定的目标元素中指定的值将用于复制其文本.这是一个使用示例:

We want to be able to attach clipboard on an element through a directive and provide as parameter the DOM element we want to link with. The value specified into the specified target element will be used to copy its text. Here is a sample of use:

<div>
  <input #foo/>
  <button [clipboard]="foo">Copy</button>
</div>

该指令的实现如下:

import {Directive,ElementRef,Input,Output,EventEmitter} from 'angular2/core';
import Clipboard from 'clipboard';

@Directive({
  selector: '[clipboard]'
})
export class ClipboardDirective {
  clipboard: Clipboard;

  @Input('clipboard')
  elt:ElementRef;

  @Output()
  clipboardSuccess:EventEmitter<any> = new EventEmitter();

  @Output()
  clipboardError:EventEmitter<any> = new EventEmitter();

  constructor(private eltRef:ElementRef) {
  }

  ngOnInit() {
    this.clipboard = new Clipboard(this.eltRef.nativeElement, {
      target: () => {
        return this.elt;
      }
    });

    this.clipboard.on('success', (e) => {
      this.clipboardSuccess.emit();
    });

    this.clipboard.on('error', (e) => {
      this.clipboardError.emit();
    });
  }

  ngOnDestroy() {
    if (this.clipboard) {
      this.clipboard.destroy();
    }
  }
}

请参阅此plunkr示例: https://plnkr.co/edit/elyMcP5PX3UP4RkRQUG8?p =预览.

See this plunkr for a sample: https://plnkr.co/edit/elyMcP5PX3UP4RkRQUG8?p=preview.

这篇关于如何在Angular 2 Typescript中复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆