HDTuto.com

How to Copy Text to Clipboard in Angular?



This article will provide example of angular copy to clipboard directive. We will use how to copy text on button click in angular. Here you will learn angular clipboard example. We will use ngx-clipboard angular example.

In this post, i will give you simple example copy text to clipboard using ngx-clipboard npm package in angular app. you can easily use copy to clip in angular 6, angular 7, angular 8, angular 9 and angular 10.

Here, i will give you two example one simple copy text using button click event with ngx-clipboard. basically you can click on button and it will copied and you can paste text. second one we will copy text using entered input text box value in button click event. so let' see both example one by one.

Step 1: Create New App

You can easily create your angular app using bellow command:

ng new myNewApp

Step 2: Install Npm Packages

In this step, we will install clipboard and ngx-clipboard npm package for creating chart using clipboard angular 10. so let's run both command:

npm install ngx-clipboard --save

Step 3: Import ClipboardModule

Now, here we will import ClipboardModule from ngx-clipboard and then we add on declarations part. so let's update app.module.ts file as like bellow:

src/app/app.module.ts

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

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

import { FormsModule } from '@angular/forms';

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

import { ClipboardModule } from 'ngx-clipboard';

@NgModule({

imports: [ BrowserModule, FormsModule, ClipboardModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

Example 1:

Here, we will update html file as like bellow, so update it as like bellow:

src/app/app.component.html

<h1>Angular Copy to lipboard Example - HDTuto.com</h1>

<button ngxClipboard [cbContent]="'This is itsolutionstuff.com example'">Copy!</button>

Output:

Example 2:

Here, we will update html file as like bellow, so update it as like bellow:

src/app/app.component.html

<h1>Angular Copy to lipboard Example - HDTuto.com</h1>

<input type="text" #inputTarget />

<button [ngxClipboard]="inputTarget">Copy!</button>

src/app/app.component.ts

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

import { ClipboardService } from 'ngx-clipboard'

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular ' + VERSION.major;

constructor(private _clipboardService: ClipboardService){

}

copy(text: string){

this._clipboardService.copy(text)

}

}

Output:

I hope it can help you...




October 22, 2020 | Category : Other



Blog Search