← All posts

Copy Text on Click in Angular

Let me show you how you can copy the text of any HTML element in Angular. Many different ways exist to do this. But I am going to show you the most native one — without third-party solutions.


We have to do next actions:
1. Create directive
2. Added directive into html element
3. Click and copy

// Create directive
ng g directive

Add the next logic to our directive:
 — @Input — it’s for text would you like to copy it.
 — @HostListener —listener for click action.
 — onClick(event) — handler for click action.
 — event.preventDefault() — tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
 — navigator.clipboard.writeText — for copy text.

// copy-text.directive.ts
import {Directive, HostListener, Input} from '@angular/core';

@Directive({
selector: '[appCopyText]'
})
export class CopyTextDirective {

@Input() public copyText = '';

constructor() {}

@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {

event.preventDefault();
if (!this.copyText) {
return;
}
navigator.clipboard.writeText(this.copyText.toString());
}

}

Create html element using directive:

// app.component.html
<p appCopyText [copyText]="'Text has been copied'">click me to copy</p>

…that’s all…