Search code examples
javascripthtmlangulartypescriptangular-directive

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

@Directive({
  selector: '[copyOnClick]'
})
export class CopyOnClickDirective {
  @Input('copyOnClick')
  public url: any;

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

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

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

      this.copied.emit(this.url);
    };

    document.addEventListener('copy', listener, false);
    document.execCommand('copy');
    document.removeEventListener('copy', listener, false);
    console.log(this.url);
  }
}

This is the HTML code.

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

Solution

  • 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).