Copy to clipboard with angular material

Use the click event to pass the text to the handling function, in this case copyToClipboard(bookmark.location)

<span class="btn-light btn-sm" (click)="copyToClipboard(bookmark.location)" title="Copy link to clipboard">
  <i class="far fa-copy copy-link"></i><span class="copy-btn-text"></span>
</span>

To programmatically copy a string use the Clipboard which service copies text to the user’s clipboard. We use a setTimeout to visually inform the user for a brief moment that the copy was successful

import { Clipboard } from '@angular/cdk/clipboard';

export class BookmarkListElementComponent {

copyLinkButtonText = '';

  constructor(private router: Router,
              private clipboard: Clipboard) {}

  copyToClipboard(location: string) {
    const copied = this.clipboard.copy(location);
    if (copied) {
      this.copyLinkButtonText = ' Copied';
      setTimeout(() => this.copyLinkButtonText = '', 1300);
    }

  }
}

See it in action at www.codever.land:

Copy-to-clipboard-demo

See the reference link (official docs) how to use it for longer texts.

Reference - https://material.angular.io/cdk/clipboard/overview


Shared with from Codever.land. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

Dynamically expand angular material panel when condition met

Dynamically expand angular material panel when condition met code snippet Continue reading