0

Because my previous question was incorrectly marked as a Duplicate here

The top answer for what it was marked as a Duplicate for returns an error when copy pasted into an Angular application.

enter image description here

This is copy pasted exactly from the top answer and the html that was used in the question is also being used exactly copy pasted.

Any insight as to why this is refusing to work would be appreciated because this shouldn't be this much of a hassle to do such a simplistic thing such as copying (but I guess everything in Web always has to be more of a hassle than desktop development :P) I mean because clearly this error isn't happening to the 1000's of people who have likely copy pasted from that answer before so insight would be nice.

Daniel Turcich
  • 1,494
  • 2
  • 21
  • 43
  • 1
    In TypeScript, `querySelector()` returns `HTMLElement` which does not have `select()` method - `select()` is defined for `HTMLTextAreaElement` and `HTMLInputElement`. If you are sure that your `querySelector()` will always return `HTMLTextAreaElement` you can use type assertion to tell TypeScript compiler about that: `var copyTextarea = document.querySelector('.js-copytextarea') as HTMLTextAreaElement;`. Also, please, dont' post screenshots of the code, post actual code. – artem Dec 04 '17 at 22:23
  • Well i was posting a screenshot of the error. The exact java script and html can be seen in the linked question that's attached to the word Duplicate. thank you for the answer. – Daniel Turcich Dec 04 '17 at 22:26

1 Answers1

0

Thanks to Artem for his comment which adequately explains why the Javascript found in the other answer doesn't work in TypeScript and how to get it to work in TypeScript.

This is the implementation I used to get it to work in Angular w/ Angular Material.

HTML

<mat-card>
    <mat-form-field>
        <input matInput class="email-input-field" placeholder="Email" value="example@gmail.com">
    </mat-form-field>

    <button mat-raised-button color="primary" class="copy-email-button" style="vertical-align:top;" (click)="copyEmail()">
        Copy
    </button>
</mat-card>

Typescript

copyEmail()
{
    var copyTextareaBtn = document.querySelector('.copy-email-button');

    copyTextareaBtn.addEventListener('click', function(event) 
    {
        var copyTextarea = document.querySelector('.email-input-field') as HTMLInputElement;
        copyTextarea.select();
        document.execCommand('copy');
    });
}
Daniel Turcich
  • 1,494
  • 2
  • 21
  • 43