How do I copy to clipboard in Angular 2 Typescript?

前端 未结 10 1043
-上瘾入骨i
-上瘾入骨i 2020-12-03 06:45

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

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

document.exe         


        
相关标签:
10条回答
  • 2020-12-03 07:19

    i got just one method from https://github.com/pehu71/copy-component/blob/master/src/simple/copy.component.ts works even on 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);
    }
    
    0 讨论(0)
  • 2020-12-03 07:25

    The code that you mentioned is the right way to do it and it can be done in Angular 2+ too.

    I don't know what you accualy need to do, but if you, for example, have an input and a button:

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

    then all you need to do is:

    (.ts file)
    
    public copyToClipboard(): void {
      const inputElement = document.getElementById('inputId');
      (<any>inputElement).select();
      document.execCommand('copy');
      inputElement.blur();
    }
    
    0 讨论(0)
  • 2020-12-03 07:27

    This is a simple pure Angular2 and javascript solution that doesn't require any libraries and which can be used in an angular component. You could turn it into a service or make it more generic if needed but this will establish the basic idea.

    Currently browsers only allow text to be copied to the clipboard from the Selection in an or . This can implemented in 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 讨论(0)
  • 2020-12-03 07:29

    You could implement an Angular2 directive arount the clipboard.js library.

    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>
    

    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>
    

    The implementation of the directive is the following:

    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();
        }
      }
    }
    

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

    0 讨论(0)
  • 2020-12-03 07:30

    This is a simple pure Angular2 and javascript solution that doesn't require any libraries and which can be used in an angular component. You could turn it into a service or make it more generic if needed but this will establish the basic idea.

    Currently browsers only allow text to be copied to the clipboard from the Selection in an <input> or <textarea>

    In the component do something like this:

    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;
            }
        }
    }
    

    Then in the html block associated with the component, do the following:

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

    That's it! The button calls the copyElementText() function in it's component and passes it the ID of the html element to get text from and copy to the clipboard.

    The function uses standard javascript to get the element by it's ID, select it, execute the "Copy" command on the selection and then deselects it.

    0 讨论(0)
  • 2020-12-03 07:37

    Currently only for the most common APIs abstractions are implemented, mostly to be able to pass different implementations when run on the server (server side rendering (https://github.com/angular/universal) in inside a webworker where the API is not available.

    I'm pretty sure there is nothing yet for the clipboard API. There are plans to implement more wrappers though.

    0 讨论(0)
提交回复
热议问题