What is the equivalent code for navigator.clipboard.readText() in angular

4.1k views Asked by At
navigator.clipboard.readText()
  .then(text => {
    // `text` contains the text read from the clipboard
  })
  .catch(err => {
    // maybe user didn't grant access to read from clipboard
    console.log('Something went wrong', err);
  });

above code is from

I need to read from clipboard on button click in angular
How to do that ?

2

There are 2 answers

1
Eliseo On

from this TypeScript How to paste data from clipboard using a button?, using hostListener

  @HostListener("window:copy",['e'])
  windowCopy(e:ClipboardEvent){
      this.clipboardContent = window.getSelection().toString();
      console.log(this.clipboardContent)
  }
0
benshabatnoam On

By your question I see that you're missing something important. Your angular app is written in typescript, which is:

a typed superset of JavaScript that compiles to plain JavaScript

It means that the clipboard API you've mentioned is available to you in angular! as you can see in this DEMO which is using your code.

Currently typescript has the navigator type as DefinitelyTyped, but unfortunately it still doesn't contains the clipboard API since it's still a non-standard DOM APIs as you can see in this git closed issue - Missing 'Navigator.clipboard' (clipboard asynchronous API)