Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to implement Angular copy to clipboard .?

angular copy to clipboard

In this tutorial, we will learn how angular copy to the clipboard. We have seen clipboards to copy CDN input, input data, and embedded video links.

In this tutorial, we will discuss the different ways we can perform Angular clipboards. First, we will use two different third parties libraries, and second, we’ll use the custom directives to perform angular copy to clipboard. So let’s get started.

Setting up and configuring the Angular clipboard project

Let’s first create our Angular clipboard project and we have three examples of Angular clipboard to clipboard. Before starting an angular project you need to install nodejs and Angular CLI in your system. We have a tutorial on how to install Nodejs and angular in Ubuntu.

ng new clipboardApp
cd clipboardApp

Some of the Best Angular copy to clipboard

There are plenty of third parties libraries to implement Angular clipboard. We’ll list here some based on the recent update, you can select based on your requirement.

LibraryDescription
ngx-clipboardThis is one of the most downloaded angular clipboard libraries, has a size of about 122 kB and 135,063 approximately downloaded per week. It works on angular 2 and above.
ngx-copy-to-clipboardThis library allows copy content to the clipboard in Angular applications easier. It has only 59.6 kB and 166 downloads per week.

Example 1: Angular copy to clipboard using ngx-clipboard

We’ll demonstrate Angular clipboard using the third-party library ngx-clipboard. Here we first need to install this library in our project by following the command.

npm i ngx-clipboard --save


Here is a screenshot of our first example of Angular clipboard using the ngx-clipboard library.

angular copy to clipboard

After installing our ngx-clipboard library and using this library in our angular project, we need to import ClipboardModule in our app.module.ts file and let edit the app.module.ts file.

import { ClipboardModule } from 'ngx-clipboard';
...
imports: [
...
    ClipboardModule,
...
]

Implement Angular clipboard using ngx clipboard

We have imported of the ngx-clipboard module into our module. Let’s demonstrate examples of it in our Angular project. In our component typescript, we have to define a few variables and methods to copy and paste our clipboard data into Textarea. Let’s edit the app.component.ts file and add the following code.

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


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

  constructor() { }

  copied(textValue: string) {
    alert('Copied successful, you can paste now.' + textValue);
    this.tempDate = textValue;

  }

  pasteData() {
    this.pasteContent = this.tempDate;
  }
}

A copied method is called when the clipboard is copied successfully, we are showing its value by alert methods, in a real application, we can use toast to show a message for copy and paste. Let’s edit the app.component.html file to add two Textarea, one to copy its contents and the other to paste its value.

<textarea id="w3review" name="w3review" rows="4" cols="50" #inputTarget>
    At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.
</textarea>
<button (cbOnSuccess)="copied(inputTarget.value)" [ngxClipboard]="inputTarget">
Copy
</button>

<div class="pastContainer">
    <textarea name="pasteContent" cols="50" rows="4" [(ngModel)]="pasteContent">   
    </textarea>
    <button (click)="pasteData()">Paste</button>
</div>

In our Textarea first, we have added local reference variable #inputTarget and its value is added inside on clipboard copy success methods cbOnSuccess. To learn more on ngx clipboard events, check out its official npmjs site.

Example 2: Angular copy to clipboard using ngx-copy-to-clipboard

We’ll demonstrate Angular clipboard using the third-party library ngx-copy-to-clipboard. Here we first need to install this library in our project by following the command.

npm i ngx-copy-to-clipboard --save

We have to import the ngx-copy-to-clipboard module in the app.module.ts file.

Angular clipboard example
import { NgxCopyToClipboardModule } from 'ngx-copy-to-clipboard';
....

 imports: [
    ...
    NgxCopyToClipboardModule,
    ...
 ],

Now let’s implement it in our app.component.html file.

<section class="section">
    <h2>Copying data from textarea element</h2>
    <textarea name="text-content" id="text-content" rows="5" cols="33">
        Copy me here in text area of all dummy data
    </textarea>
    <ngx-copy-to-clipboard target="#text-content" 
         [success]="onSuccess" [error]="onError">
       Copy
    </ngx-copy-to-clipboard>
</section>

We have Textarea content to copy, this library we called onSuccess and onError callback methods. We have not implemented the on-paste content method, which is the same one you can refer to in our previous example. Now let’s edit the app.component.ts file to define onSuccess and onError methods.

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

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

  constructor() { }

  onSuccess(e) {
    this.copiedText = e.text;
  }

  onError(e) {
    this.copiedText = 'Error trying to copy your text';
  }
}

Example 3: Custom directive to perform Angular clipboard

In both our previous examples, we have used third parties libraries and we can create our own custom directives to perform the same clipboard activities. Let’s create our directive by running the following command.

npm g directive directives/copy

I have found this code in the stackblitz on this link, code is written by someone else and is in Angular 6. We’ll try it in Angular 11, to check if it still works. Let’s edit the copy.directive.ts file to add our custom angular clipboard code.

import { Directive, ElementRef, Renderer2, OnInit } from "@angular/core";
  
  @Directive({
    selector: "[appCopy]"
  })
  export class CopyDirective implements OnInit {
    constructor(private _el: ElementRef, private _renderer: Renderer2) {}
  
    ngOnInit() {
      let copy_icon = this._renderer.createElement("i");
      this._renderer.addClass(copy_icon, "fa");
      this._renderer.addClass(copy_icon, "fa-copy");
      this._renderer.addClass(copy_icon, "angular-copy-icon");
      this._renderer.setStyle(copy_icon, "margin-left", "5px");
      let simple = this._renderer.listen(copy_icon, "click", evt => {
        this.copy(this._el.nativeElement);
      });
  
      this._renderer.appendChild(this._el.nativeElement.parentNode, copy_icon);
    }
  
    copy(event) {
      let input = event;
      input.select();
      document.execCommand("copy");
      input.setSelectionRange(-1, -1);
    }
  }

In this directive add font awesome icon on input, we have a tutorial on how to add font awesome on our angular project and at the end, it has executed document exCommand copy on our input.

To use this directive we have to declare on our module, in our case we have only one module which is the app.module.ts file.

..
import { CopyDirective } from './directives/copy.directive';

@NgModule({
  declarations: [
    AppComponent,
    CopyDirective
  ],
  imports: [
    ..
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Angular clipboard example
angular copy to clipboard

You can see the paste icon on input, let’s add our copy directive on our input in our component template.

<div>
   <label>Sample text from custom directive: </label>
   <input appCopy type="text" #text1 value="hello world">
</div>
Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Conclusion
We have completed three examples of how to add an Angular clipboard to our Angular application using two different third-party libraries and custom directives.

Related posts

How to implement Angular copy to clipboard .?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top