Angular 10|9 Copy to Clipboard using Material or ngx-clipboard package

In this Angular tutorial, we’ll learn how to implement Copy to Clipboard feature in Angular 10/9/8/7/6/5/4 application by using two ways.

Copy to Clipboard feature is required in an application to facilitate the user to quickly copy a text or content. Like we can have Cuopns, Offer codes, Some poems, Lyrics, etc which is intended to be copied by users.

For this to get happened, we simply add a button using which a user just clicks on a button to copy the test without any mouse or keyboard operations.

In Angular application, we can easily implement Copy to Clipboard feature in two ways:

Angular Material: If you are using the Material UI package in your application, then there is no need to incorporate any third-party package. You can just use the ClipboardModule API and start using the feature.

NPM package: If your Angular application is not using Material, then we can install the best available NPM package, to provide Copy to Clipboard feature in few steps.

Here we’ll be explaining both ways for any type of Angular project with step by step procedure. So let’s get started!

 

Setup Angular CLI

First, install or update the Angular CLI tool to the latest version by running the below NPM command

$ npm install -g @angular/cli

You can check the version of Angular currently installed

$ ng --version
Angular CLI: 10.0.3
Node: 12.15.0
OS: win32 x64

 

Create a New Angular Application

Run following ng command to create a new Angular project

$ ng new angular-copy-to-clipboard-app
# ? Would you like to add Angular routing? No
# ? Which stylesheet format would you like to use? SCSS

Enter the project directory

$ cd angular-copy-to-clipboard-app

Run the application

$ ng serve --open

 

Implement Copy to Clipboard Feature

Now we are going to implement Copy to Clipboard feature in our newly created Angular application. First, we’ll get to know how to use the NPM package then will install Angular Material to use its API for the same.

 

Method #1: Using NPM Package

In this method, we’ll use the ngx-clipboard package to implement the CTC feature.

 

Install ngx-clipboard Package

Run following npm command in the project root to install the package

$ npm install ngx-clipboard --save

 

Update App Module

Now open the app.module.ts file to import the ClipboardModule from 'ngx-clipboard'. Then update the imports Array as shown below:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { ClipboardModule } from 'ngx-clipboard';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    ClipboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Using Copy to Clipboard

# Copy Inline String

The ngxClipboard directive with [cbContent] property can be directly added in the template HTML to copy inline small texts

<div #container>
  <button ngxClipboard [cbContent]="'Some Small Inline Text to Copy!'" [container]="container">Copy</button>
</div>
# Copy Text from Input Form Control

Custom text entered inside the form control can be fetched by adding a template reference variable #someInputControl then assign to the [ngxClipboard] directive

<input type="text" #someInputControl />
<button [ngxClipboard]="someInputControl">Copy</button>

 

# Copy from Component Class Event

We can import the ClipboardService in the component to use its copyFromContent() function to copy any dynamic value.

Template HTML

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

Component Class

// app.component.ts
import { Component } from '@angular/core';
import { ClipboardService } from 'ngx-clipboard';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-copy-to-clipboard-app';

  constructor(
    private _clipboardService: ClipboardService
  ) { }

  copyDynamicText() {
    this._clipboardService.copyFromContent(this.title)
  }
}
# Callback Events

The (cbOnSuccess) event callback is called after copying is successful.

Angular 10|9 Copy to Clipboard using Material or ngx-clipboard package

Template HTML

<h4>Today's Lucky Coupon</h4>

<div [ngClass]="isCopied ? 'lucky-coupon coupon-applied' : 'lucky-coupon'">

  <div class="lucky-coupon-code">{{couponText}}</div>

  <ng-container *ngIf="isCopied; else elseTemplateCopied">

    <div class="coupon-copied">Copied!</div>

  </ng-container>
  <ng-template #elseTemplateCopied>

    <div (cbOnSuccess)="copied($event)" ngxClipboard [cbContent]="couponText">
      <div class="copy-code">✂️</div>
    </div>

  </ng-template>
</div>

Component Class

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  couponText = 'FREAKYDISCOUNT 50%';

  isCopied = false;

  copied(event) {
    this.isCopied = event.isSuccess;
  }
}

CSS Style

/* Copy paste */
.coupon-applied {
    border-color: green !important;
    background: #bdffb4;
}
.lucky-coupon {
    border: 5px dashed #ccc;
    width: 320px;
    display: inline-block;
    font-size: 1.2em;
}

.lucky-coupon-code {
    padding: 15px;
    display: inline-block;
    float: left;
    font-weight: bold;
}

.copy-code {
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.coupon-copied {
    padding: 13px 0px;
    display: inline-block;
    color: green;
    font-size: 19px;
}

 

Method #2: Using Angular Material API

Now we’ll discuss how to implement using Material package API

 

Install Material Package

Run the following command to install the Material package

$ ng add @angular/material

Answer a few questions asked to do configuration in the Angular project

# ? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink
# ? Set up global Angular Material typography styles? Yes 
# ? Set up browser animations for Angular Material? Yes

Update App Module

After installation is complete, we’ll import the required API Material modules in the app.module.ts file. To implement the Copy to Clipboard feature, import the ClipboardModule then update the imports array:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ClipboardModule } from '@angular/cdk/clipboard';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,

    ClipboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Using Material Copy to Clipboard

The cdkCopyToClipboard directive can be used to easily add copy-on-click functionality to any existing element. This directive takes a variable or string which needs to be copied on click.

# Copy Inline Template

Template HTML

<span [cdkCopyToClipboard]="'Copy Some Span Text'">Copy Text</span>

<button [cdkCopyToClipboard]="variableWithText">Copy Text</button>

<div [cdkCopyToClipboard]="dynamicText()">Copy Text</div>

 

Component Class

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  variableWithText = "Some Random Text in the Variable";

  dynamicText() {
    return "Some Dynamic text returned to be copied";
  }
}

 

# Programmatically copy a string

Import the Clipboard class and add inside the constructor()

// app.component.ts
import { Component } from '@angular/core';
import { Clipboard } from '@angular/cdk/clipboard';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  variableWithText = "Some Random Text in the Variable";

  constructor(private clipboard: Clipboard) { }

  copyDynamicText() {
    this.clipboard.copy(this.variableWithText);
  }

}

 

That’s it now you can run Angular application to see it working.

 

Conclusion

Finally, we are done with the tutorial on How to implement Copy to Clipboard feature functionality in Angular application using a Material package API ClipboardModule or third-party NPM package module named ngx-clipboard.

If you are not using the Material library then it’s preferred to use the NPM package instead of installing Material for a single feature. On the other side if your Angular application already using material UI components, then its better to use the Clipboard API module.

Do share your feedback and comments…

Stay Safe!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments