How to copy text in Angular (The Definitive Guide)


Today you're going to learn how to copy text in Angular.

That is, I'm going to show you exactly how to copy text to the clipboard programmatically.

The best part?

There are 4 different ways to do this. And you get to pick the option that will work best for you.

Let's dive right in and start copying text in our Angular app.

ron-fung-VQJXJ4IaU_o-unsplash

1. Copying text with the Angular CDK

Given that Angular Material and the CDK are a common dependency in Angular project maybe you've already got it installed?

If not, the first step is to install the Angular CDK. Like this.

ng add @angular/material

Next, we'll have to import the Clipboard Module into our app.module.ts file

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ClipboardModule } from '@angular/cdk/clipboard';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ClipboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And that brings us to the last step - using the CDK directive to copy text to the clipboard.

<button cdkCopyToClipboard="Angular copy text demo">Copy text</button>

When the "Copy text" button is clicked the text "Angular copy text demo" will be copied to the clipboard.

Simple, eh? 🤩

But there's more than one way to skin this cat.

2. Using the ngx-clipboard to copy text

Turns out there's a popular library called ngx-clipboard that was created specifically for Angular apps to copy text to the clipboard.

At the time of this writing it has averaged around 130,000 downloads per week.

Not to mention that it also has some cool features like...

  • No other JavaScript dependencies or requirements (protecting it from rogue libraries).
  • Supports Angular vs2 and up (don't have to upgrade your Angular app to use it).
  • 25+ contributors (plenty of community power behind this project).

Before we can use it we'll have to first install it. 😼

npm install ngx-clipboard --save

Once installed we'll import the package into our app.module.ts file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ClipboardModule } from 'ngx-clipboard';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ClipboardModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And last of all, we'll use the ngx-clipboard library to copy a string to the clipboard.

<button ngxClipboard cbContent="Angular copy text demo">Copy text</button>

You can also set up an input target like this - the text that is in the textarea will automatically be copied to the clipboard.

<textarea #inputTarget></textarea>
<button [ngxClipboard]="inputTarget">Copy</button>

3. Avoiding dependencies and building our copy text function

But what if we want to copy text without having to depend on a 3rd-party library?

I think this is a great approach to consider, especially if we only need a simple copy function in one obscure place of our Angular project.

Building our own copy function comes with advantages like...

Here's how we create a simple copy text function for an Angular component.

We'll begin with the TypeScript file.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './copy.component.html',
  styleUrls: ['./copy.component.css']
})
export class CopyComponent {  
  clipboardValue = 'Angular copy text demo';

  copyText(): void {
    navigator.clipboard.writeText(this.clipboardValue).catch(() => {
      console.error("Unable to copy text");
    });
  }
}

And last of all the HTML template.

<button (click)="copyText()">Copy</button>

4. Creating our own copy text directive

It's as simple as 1... 2... and... 3.

1st step: Generate the copy-clipboard directive with the [Angular CLI]().

ng generate directive copy-clipboard

2nd step: Here's the code for your new directive.

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[copyClipboard]'
})
export class CopyClipboardDirective {
  @Input("copyClipboard")
  public payload: string = "";

  @HostListener("click", ["$event"])
  public onClick(event: MouseEvent): void {

    event.preventDefault();
    if (!this.payload)
      return;

    navigator.clipboard.writeText(this.payload.toString());
  }

}

3rd step: Use the Angular clipboard directive like this.

<button copyClipboard="Angular clipboard demo">Copy</button>

Kudos go to Dan for his awesome answer on Stack Overflow that inspired this solution.

Which approach are you using?

My personal favorite is the ngx-library for projects that require a lot of copy functionality.

Why?

It's loaded with fancy features and is pretty popular.

But for simpler projects I'd prefer to create my own function or use a copy text directive.

But what do you say?

Which one did you chose to use? Let me know in the comments below. 👇 👇 👇

signature

Angular Consulting