Copy to Clipboard is one of the very common requirement in many front-end web applications. Achieving this with older Browser APIs used to a tedious process and developers generally used to depend on one or the other third party library to do so.

With modern Browser APIs implementing Copy to Clipboard can be achieved very easily in Angular 12/13 or any other front-end application.

Suppose we have the following HTML in an Angular application

<div>
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Maiores minus excepturi in consectetur perferendis non
    facilis laborum, eum suscipit! Iusto!
</div>

<button class="btn btn-primary">Click To Copy To Clipboard</button>

We want to copy the contents of the above Div element, when the user clicks on the button below. To achieve this, first we need to pass the contents of the Div element to the TS file, when the user clicks on the button. There are multiple ways to access the contents of an element in the TS file in an Angular application, for our example, we can create a Template Reference Variable and pass it through event binding like this

<div #elementContentToCopy>
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Maiores minus excepturi in consectetur perferendis non
    facilis laborum, eum suscipit! Iusto!
</div>

<button class="btn btn-primary" (click)='copyToClipboard(elementContentToCopy)'>Click To Copy To Clipboard</button>

then, we can access this inside the component TS file, like this

copyToClipboard(el: HTMLDivElement) {
    console.log(el.innerText);
  }

Now, its time to implement the copy to clipboard functionality. We can do it by writing the text to the clipboard property of the navigator object of the browser.

example:

navigator.clipboard.writeText('Text to copy')

Since these APIs are relatively new, even though most of the current browsers supports this feature, we can still check the browser compatibility then implement it.

full code:

copyToClipboard(el: HTMLDivElement) {
    console.log(el.innerText);

    if (navigator.clipboard) {
      navigator.clipboard.writeText(el.innerText).then(() => {
        alert('Copied to Clipboard')
      }, (error) => {
        console.log(error)
      });
    } else {
      console.log('Browser do not support Clipboard API')
    }

  }