João
João

Reputation: 31

I need to make a copy for clipboard taking a dynamic variable angular

HTML

OBS: The Technical.url specification variable is dynamic, whenever I click the button I want to copy the url.

<div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="">
    <span>{{technicalSpecification.url}}</span>
</div>

<div fxLayout="column" fxLayoutAlign="center end" fxFlex="10">
    <button mat-icon-button>
        <mat-icon matTooltip="Copy Service URL""> content_copy </mat-icon>
    </button>
</div>

Upvotes: 0

Views: 476

Answers (2)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

Here is the function which I am using for the copy to clipboard

DEPRECATED FOR MORE INFO

copyToClipboardHelper(text: string) {
  const textArea = document.createElement('textarea');
  textArea.value = text;

  // Avoid scrolling to bottom
  textArea.style.top = '0';
  textArea.style.left = '0';
  textArea.style.position = 'fixed';

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  let successful = false;
  try {
    successful = document.execCommand('copy');
  } catch (err) {
    console.error('Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);

  return !!successful;
}

YOUR HTML Template

<div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="">
    <span>{{technicalSpecification.url}}</span>
</div>

<div fxLayout="column" fxLayoutAlign="center end" fxFlex="10">
    <button mat-icon-button (click)="copyToClipboardHelper(technicalSpecification.url)">
        <mat-icon matTooltip="Copy Service URL""> content_copy </mat-icon>
    </button>
</div>

Upvotes: 0

robert
robert

Reputation: 6152

You mean something like this:

<div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="">
    <span>{{technicalSpecification.url}}</span>
</div>

<div fxLayout="column" fxLayoutAlign="center end" fxFlex="10">
    <button mat-icon-button (click)="onCopy()">
        <mat-icon matTooltip="Copy Service URL""> content_copy </mat-icon>
    </button>
</div>

TS:

onCopy(): void {
  navigator.clipboard.writeText(this.technicalSpecification.url).then(function() {
  /* clipboard successfully set */
}, function() {
  /* clipboard write failed */
});
}

Upvotes: 1

Related Questions