0

How do I make a button copy an input value to the clipboard?

I've seen this: How do I copy to clipboard in Angular 2 Typescript?

but it's not longer compactible from the latest angular changes with ngModule (RC5+)

Community
  • 1
  • 1
TheUnreal
  • 23,434
  • 46
  • 157
  • 277
  • What is the issue? What have you tried? https://plnkr.co/edit/ryF9DqDaIPIbQvKLp3OU?p=preview – yurzui Sep 15 '16 at 18:52

3 Answers3

1

You can use many different libraries to accomplish this task in a few different ways. Problem is, they are not well documented and are kind of use-case specific. Take some time to learn about Document from angular/core. Here's the solution I ended up with:

import { Component, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';

import { AuthService } from '../auth.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

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

  }

  ngOnInit() {
  }


  onCopy() {
    var el = this.document.getElementById('targetDiv')
    el.setAttribute('contenteditable','true')
    el.focus()
    this.document.execCommand('selectAll')
    this.document.execCommand('copy');
    el.setAttribute('contenteditable','false')
    el.blur()
  }


}

And in template

<div id="targetDiv" contenteditable="false">
 <p><strong>Test: </strong> 1 2 3 4 </p>
 <h2> mic check    </h2>
</div>

<button mat-raised-button (click)="onCopy()" >
 Copy
</button>
0

Here is RC7 version of the same.

Working Demo : https://plnkr.co/edit/hSP42BLoxX2uodZZ2uMj?p=preview

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }   from './app.component';
import {FormsModule} from '@angular/forms';
import {ClipboardDirective} from './clipboard.directive';
@NgModule({
  imports:      [ BrowserModule,FormsModule ],
  declarations: [ AppComponent,ClipboardDirective ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
micronyks
  • 54,797
  • 15
  • 112
  • 146
0

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();
}
Shiju Augustine
  • 265
  • 1
  • 4
  • 11