Angular 2 Directives Copy to Clipboard directive


In this example we are going to create a directive to copy a text into the clipboard by clicking on an element


import {
} from "@angular/core";

    selector: '[text-copy]'
export class TextCopyDirective {

    // Parse attribute value into a 'text' variable
    @Input('text-copy') text:string;

    constructor() {

    // The HostListener will listen to click events and run the below function, the HostListener supports other standard events such as mouseenter, mouseleave etc.
    @HostListener('click') copyText() {

        // We need to create a dummy textarea with the text to be copied in the DOM
        var textArea = document.createElement("textarea");

        // Hide the textarea from actually showing = 'fixed'; = '-999px'; = '-999px'; = '2em'; = '2em'; = '0'; = 'none'; = 'none'; = 'none'; = 'transparent';

        // Set the texarea's content to our value defined in our [text-copy] attribute
        textArea.value = this.text;

        // This will select the textarea;

        try {
            // Most modern browsers support execCommand('copy'|'cut'|'paste'), if it doesn't it should throw an error
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            // Let the user know the text has been copied, e.g toast, alert etc.
        } catch (err) {
            // Tell the user copying is not supported and give alternative, e.g alert window with the text to copy
            console.log('unable to copy');

        // Finally we remove the textarea from the DOM

export const TEXT_COPY_DIRECTIVES = [TextCopyDirective];


Remember to inject TEXT_COPY_DIRECTIVES into the directives array of your component

    <!-- Insert variable as the attribute's value, let textToBeCopied = '' -->
    <button [text-copy]="textToBeCopied">Copy URL</button>
    <button [text-copy]="''">Copy URL</button>