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.execCommand('copy')
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.execCommand('copy')
Ben Nadel had a great example that worked for any html element type and doesn't rely on anything to be installed. See Ben's blog post Or see the Git gist
See his blog for more about it and the logging he does, here's the relevant and slightly modified so it fits here better:
Make a directive: clipboard.directive.ts
And a service clipboard.service.ts
Import both in the app.module.ts and then you can reference it in html with something like this:
Kudos to @ThierryTemplier,
Base on his answer, I put together a directive and sharing on github & npm.
Here is the project on github
UPDATE: 4/30/2017
This library doesn't depends on clipboard.js anymore.
Just Angular !
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:
Then in the html block associated with the component, do the following:
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.
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.
You could implement an Angular2 directive arount the clipboard.js library.
First configure the library into SystemJS:
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:
The implementation of the directive is the following:
See this plunkr for a sample: https://plnkr.co/edit/elyMcP5PX3UP4RkRQUG8?p=preview.
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