DEV Community

Cover image for How to copy to clipboard with angular material
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3

How to 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">{{copyLinkButtonText}}</span>
</span>


Enter fullscreen mode Exit fullscreen mode

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);
    }

  }
}


Enter fullscreen mode Exit fullscreen mode

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. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay