Welcome folks today in this blog post we will be integrating copy text to clipboard
inside textarea on button click in typescript using ngx-clipboard
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library
using the below command as shown below
npm i ngx-clipboard
After that you will see the below directory
structure as shown below
As you can see we now need to go to app.module.ts
file and copy paste the following code
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 |
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 {} |
And then you need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 |
<div #container> <button ngxClipboard [cbContent]="'John Williamson'" [container]="container">Copy</button> <textarea name="" id="" cols="30" rows="10"></textarea> </div> |
As you can see in the above html
code we have the button in which we have attached the copy to clipboard
directive and also we have the textarea
where we have copy pasted the text.
Copy to Clipboard Dynamically
And now you need to go to app.component.ts
file and copy paste the following code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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 { text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; constructor(private clipboardService: ClipboardService) {} copyContent() { this.clipboardService.copyFromContent(this.text); } } |
And now in the above typescript
code we are importing the clipboardservice
from the ngx-clipboard
library and then we are declaring the text
to be copied and then we declaring the method
called copyContent()
method which would dynamically copy
the text to clipboard.
1 2 3 |
<div #container> <button (click)="copyContent()">Copy Me</button> </div> |