Angular [cdkCopyToClipboard] beeing called repeatedly

Viewed 2165

I am using the ClipboardModule from @angular/cdk/clipboard to copy data from my angular form, the problem is that i just realized that my CopyDeatils() method is being called continuously but the value is only copied when the button is pressed.

here is my code:

CopyDetails(): string {       
        return "details ...";       
    }

and this is how it is being called:

<button [cdkCopyToClipboard]="CopyDetails()" type="button">Copy</button>

1 Answers

I assume you're using default change detection. In that case the function will be called multiple times based on refresh cycle. You could instead bind the cdkCopyToClipboard to variable and use either mouseup or click event handler to bind the function. Try the following

Controller

copyToClipboard: string;

CopyDetails(): string {
  ...       
  copyToClipboard = "details ...";       
}

Template

<button 
  (mouseup)="CopyDetails()"
  [cdkCopyToClipboard]="copyToClipboard" 
  type="button"
>Copy</button>

Edit: move (mouseup) event handler before [cdkCopyToClipboard] binding based on OP's comment

Related