[Fixed] Angular 10: I am trying to copy the string data from a span with out using the @Input brackets in the HTML


I am trying to copy the elements from a span, input, button, etc. without the [ ] around the Input like so <button copyOnClick>testing the data</button> which should copy testing the data. it does work when I do have the brackets around the copyOnClick <button [copyOnClick]="index + 1"> {{index + 1}}</button> which copies 1 but I wanted to get the text inside the button so it can be a bit more dynamic if I added it to a span or input as well.

This is my Directive

  selector: '[copyOnClick]'
export class CopyOnClickDirective {
  public url: any;

  public copied: EventEmitter<string> = new EventEmitter<string>();

  @HostListener('click', ['$event'])
  public onClick(event: MouseEvent): void {
    if (!this.url) return;

    let listener = (e: ClipboardEvent) => {
      let clipboard = e.clipboardData || window['clipboardData'];
      clipboard.setData('text', this.url.toString());


    document.addEventListener('copy', listener, false);
    document.removeEventListener('copy', listener, false);

This is the HTML code.

<button class="btn-numbers btn font-weight-medium btn-light" [copyOnClick]="index + 1">{{ index + 1 }}</button>


What you want to do is inject the host element ref into the directive constructor (private readonly _elementRef: ElementRef) and use this to get the actual content.

Then you can use this._elementRef.nativeElement to access the inner html (for spans) or the value (for text inputs).

Leave a Reply

(*) Required, Your email will not be published