web-dev-qa-db-ja.com

Angular 2 Typescriptでクリップボードにコピーするにはどうすればよいですか?

Angular2 TypeScriptフレームワークのクリップボード(マルチブラウザ)にテキストをコピーする方法はありますか?

Javascriptを使用するソースのみを見つけます。

document.execCommand('copy')
21
Andris Krauze

clipboard.js ライブラリを回避するためにAngular2ディレクティブを実装できます。

最初にライブラリをSystemJSに設定します。

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

ディレクティブを使用してクリップボードを要素にアタッチし、リンクするDOM要素をパラメーターとして提供できるようにします。指定されたターゲット要素に指定された値は、そのテキストをコピーするために使用されます。使用例は次のとおりです。

<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=preview

36

@ThierryTemplierに称賛、

彼の答えに基づいて、私はgithubとnpmでディレクティブと共有をまとめました。

github のプロジェクトはこちら

更新:2017年4月30日

このライブラリはclipboard.jsに依存しなくなりました。

ちょうどAngular!

24
maxisam

私は https://github.com/pehu71/copy-component/blob/master/src/simple/copy.component.ts Android 4.1.2でも動作します

copy(val) {

    let selBox = document.createElement('textarea');

    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;

    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();

    document.execCommand('copy');
    document.body.removeChild(selBox);
}
21
dimson d

これは単純なpure Angular2およびjavascriptソリューションで、はライブラリを必要としませんおよびangularコンポーネントで使用できます。必要に応じてサービスに変換したり、より汎用的にしたりできますが、これにより基本的な考え方が確立されます。

現在、ブラウザでは、<input>または<textarea>内のSelectionからクリップボードにテキストをコピーすることのみが許可されています

コンポーネントで次のようなことを行います。

import {Inject} from "@angular/core";
import {DOCUMENT} from "@angular/platform-browser";

export class SomeComponent {
    private dom: Document;

    constructor(@Inject(DOCUMENT) dom: Document) {        
       this.dom = dom;
    }

    copyElementText(id) {
        var element = null; // Should be <textarea> or <input>
        try {
            element = this.dom.getElementById(id);
            element.select();
            this.dom.execCommand("copy");
        }
        finally {
           this.dom.getSelection().removeAllRanges;
        }
    }
}

次に、コンポーネントに関連付けられたhtmlブロックで、次を実行します。

<div>
   <button (click)="copyElementText('elem1')">Copy</button>
</div>
<textarea id="elem1">Some text</textarea>

それでおしまい!ボタンは、コンポーネントのcopyElementText()関数を呼び出し、html要素のIDを渡して、テキストの取得とコピーを行いますクリップボード。

この関数は、標準のJavaScriptを使用して、そのIDで要素を取得し、それを選択し、選択に対して「コピー」コマンドを実行してから選択を解除します。

3
Cliff Ribaudo

テキストが入力またはテキストエリア内ではなく、div、またはその他のHTMLElement内にある場合の簡単なコードを次に示します。

_window.getSelection().selectAllChildren(document.getElementById('yourID');
document.execCommand("Copy");
_

select()コマンドは、Angularによって認識されなかったため使用できませんでした。これが誰かを助けることを願っています!

2
Pablo Quemé

現在、最も一般的なAPIの抽象化のみが実装されており、主にサーバーで実行するときに異なる実装を渡すことができます(サーバー側レンダリング( https://github.com/angular/universal ) APIが利用できないウェブワーカー。

クリップボードAPIにはまだ何もないと確信しています。ただし、さらにラッパーを実装する計画があります。

1

あなたが言及したコードはそれを行う正しい方法であり、Angular 2+でも実行できます。

あなたが実際に何をする必要があるのか​​わかりませんが、たとえば、入力とボタンがある場合:

(.html file)

<input id='inputId'></input>
<button (click)="copyToClipboard()'>click me</button>

その後、あなたがする必要があるのは:

(.ts file)

public copyToClipboard(): void {
  const inputElement = document.getElementById('inputId');
  (<any>inputElement).select();
  document.execCommand('copy');
  inputElement.blur();
}
0
pbialy

Clipboard API を使用することによってのみ、外部の依存関係や偽の要素を作成せずにこれを実現する方法を次に示します。

import { DOCUMENT } from '@angular/common';
import { Directive, EventEmitter, HostListener, Inject, Input, Output } from '@angular/core';

@Directive({
  selector: '[myClipboard]'
})
export class ClipboardDirective {

  @Input() myClipboard: string;
  @Output() myClipboardSuccess = new EventEmitter<ClipboardEvent>();

  constructor(@Inject(DOCUMENT) private document: Document) {}

  @HostListener('click')
  onClick() {
    this.document.addEventListener('copy', this.handler);
    this.document.execCommand('copy');
  }

  private handler = (e: ClipboardEvent) => {
    e.clipboardData.setData('text/plain', this.myClipboard);
    e.preventDefault();
    this.myClipboardSuccess.emit(e);
    this.document.removeEventListener('copy', this.handler);
  }

}

クリップボードAPIを使用できますか?

0
s.alem

これは、ライブラリを必要とせず、angularコンポーネントで使用できる、単純な純粋なAngular2およびjavascriptソリューションです。これにより、基本的な考え方が確立されます。

現在、ブラウザでは、またはの選択からテキストをクリップボードにコピーすることのみが許可されています。これはdivで実装できます

(.html file)
<div id="inputId">Some texts</div>
<button (click)="copyToClipboard()'>click me</button>

//(.ts file)

public copyToClipboard(){
  var el = document.getElementById('inputId');
  el.setAttribute('contenteditable','true');
  el.focus();
  document.execCommand('selectAll');
  document.execCommand('copy');
  el.setAttribute('contenteditable','false');
  el.blur();
}
0
Shiju Augustine