Wednesday, December 09, 2020

Angular Clipboard Service

It's about time I post something new! Since my last post I've had to learn and build applications in the Ember, React, and now Angular JavaScript Frameworks.  Along the way I've learned some interesting tips and tricks I can share here.

I needed the ability to place content in the clipboard, but needed it lots of placed throughout the application. So here's a simple Clipboard service that will place any string into the clipboard.  I incorporated the use of MatSnackBar to notify the user that the value has been placed in the clipboard.

import {Injectable, Renderer2, RendererFactory2} from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';

  providedIn: 'root'
export class ClipboardService {
  private renderer: Renderer2;

  constructor (
      private rendererFactory: RendererFactory2,
      private snackBar: MatSnackBar,
      ) {
    // Get an instance of Angular's Renderer2
    this.renderer = this.rendererFactory.createRenderer(null, null);

  copy(value: string) {

    // create an temporary text input field to contain the value and select the value
    const input = this.renderer.createElement('input');
    this.renderer.setProperty(input, 'value', value);
    this.renderer.appendChild(document.body, input);
    input.setSelectionRange(0, 99999); // For mobile devices

    // Copy the selected text inside the text field to the clipboard
    document.execCommand('copy');`Copied "${value}" to clipboard`, undefined, { duration: 1000 });

    // remove the temporary text input field
    this.renderer.removeChild(document.body, input);

You then simply inject it into any component that needs it:

import { ClipboardService } from 'clipboard.service';

constructor( private clipboard: ClipboardService ) {} 

and then copy whatever values you want to the clipboard simply as: