How To Create Copy To Clipboard In Angular

This functionality can be used to easily add copy-on-click. basically you can click on button and it will copied and you can paste text. here we are using ngx-copy-to-clipboard. we need to install ngx-copy-to-clipboard using below npm :

npm i ngx-copy-to-clipboard

In file app.component.ts

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

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

  copiedText = "";

  constructor() {
    this.onSuccess = this.onSuccess.bind(this);
    this.onError = this.onError.bind(this);
  }

  onSuccess(event:any) {
    this.copiedText = event.text;
  }

  onError(event:any) {
    this.copiedText = "Please enter any text.";
  }

}

In file app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxCopyToClipboardModule } from 'ngx-copy-to-clipboard';
import { AppComponent } from './app.component';

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

  ],

  bootstrap: [AppComponent]
})

export class AppModule { }

In file app.component.html

<textarea name="text-content" class="mt-5 ms-5" id="text-content" rows="5" cols="33">Enter any text here...</textarea>

<ngx-copy-to-clipboard
class="d-block ms-5"
target="#text-content"
[success]="onSuccess"
[error]="onError"
>Copy</ngx-copy-to-clipboard>

<code class="mx-5">{{ copiedText || 'Your text will be pasted here...' }}</code>

output :

Submit a Comment

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

Subscribe

Select Categories