1

Say I have a markup something like the following:

<ul someSelector>
    <li>Item 1</li>
    <li>Item 2</li>
    ...
</ul>

And I have a directive something like this:

@Directive({
    selector: '[someSelector]'
})
export class SomeDirective {

    @HostListener('click') someFunction() {
        // Know which child LI that was clicked on at this point;
        // Say I want to add some class to that LI
    }

}

Clicking on any of the list items will invoke (the directive and) someFunction() method. In the scope of the method, I want to know which of the list item was clicked. Is this possible?

I could create another directive and place it in each <li> but since the parent already has a directive I feel it's an overkill to do that.

@HostListener documentation wasn't very helpful.

Dilip Raj Baral
  • 3,060
  • 6
  • 34
  • 62

1 Answers1

2
<ul appSomedirective>
    <li>Item 1</li>
    <li>Item 2</li>
    ...
</ul>


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

    @Directive({
      selector: '[appSomedirective]'
    })
    export class SomedirectiveDirective {
    numberOfClicks:Number;
      constructor() { }
     @HostListener('click', ['$event.target'])  someFunction(event) {
        debugger;
         console.log("button", event.innerText, "number of clicks:");

        }
    }

It's Working fine, You may try this.

Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21