1

I've created an Angular Attribute Directive, which can be added to a button or link and implement some kind of click tracking. Please see a simplified example here:

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appTrackClick]'
})
export class TrackClickDirective {
  @Input() trackType = 'ButtonClick';
  @Input() trackName: string;

  @HostListener('click') onClick() {
    this.trackClick()
  }

  constructor() { }

  trackClick() {
    if (!this.trackName) {
      return false;
    }
    // Do the tracking...
  }
}

I would like the value of this.trackName to be the text of the button or link clicked. How do I get this information from the element?

If possible, I'd like to do this just in the Typescript, and not have to add any more markup to the template.

3
  • Inject an ElementRef into the constructor: it will be a reference to the button/link being clicked. Of course, I hope you realize that not all buttons/links have text (it could just be an image, or a large piece of HTML). Commented Mar 21, 2019 at 11:51
  • Thanks @JBNizet, could you provide a full example as an answer so I can mark it as correct (if it works)? Commented Mar 21, 2019 at 11:53
  • 1
    stackblitz.com/edit/… Commented Mar 21, 2019 at 11:58

1 Answer 1

5

You can just inject the ElementRef in the directive and get access to the host DOM element.

You can see more about Directives and ElementRef here:

You use the ElementRef in the directive's constructor to inject a reference to the host DOM element, the element to which you applied the directive.

@Directive({
  selector: '[appTrackClick]'
})
export class TrackClickDirective {
  @Input() trackType = 'ButtonClick';
  @Input() trackName: string;

  @HostListener('click') onClick() {
    this.trackClick()
  }

  constructor(private elementRef: ElementRef) { }

  trackClick() {
    if (!this.trackName) {
      return false;
    }
    console.log('Element text: ', this.elementRef.nativeElement.innerText);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.