How to copy text to clipboard in Angular

ZeroesAndOnes
4 min readAug 24, 2021

In this article I will show you how to copy text to clipboard in your Angular project leveraging the Clipboard service provided by Angular framework.

1 — Create an empty Angular Project

First, let’s start off by creating an empty Angular project. To do that open a Terminal in your VScode and type the following command:

> ng new ClipboardExample

and make sure to follow the command prompts. This might take a bit to complete because Angular is going to download its required packages. Below is a link to an article that I have created that will show you how to create an empty Angular 9 project along with all the necessary requirements.

2 — Install the CDK package in your Angular project

In order to use the Clipboard service you must install the CDK package in your project. The barebone Angular project does not include the CDK package.

In your Angular project terminal type the following command to download the package using npm:

npm install @angular/cdk

3 — Inject Clipboard service in the constructor of the component

The Clipboard service contains two methods:

  1. beginCopy — This method is designed to prepare a string to be copied later. This is mainly used when a large string is about to be copied. Large strings may take too long to successfully render and be copied in the same tick.
  2. copy— This method is designed to copy the provided text into the user’s clipboard. The method returns a boolean value indicating whether the operation was successful.

In order to use these methods inside your component you will need to inject the Clipboard service in the component’s construction. Once injected, you will be able to reference/call any of the two methods.

Below is how you can reference the Clipboard service. All you have to do is add a private parameter called “clipboard” (you can name it anything you would like) and must be of type Clipboard.

--

--