0

I have a component and i have the following elements in component's html and need the element's id on clicking it. Example: on clicking

  • element with id "l1", i should receive l1 inside onclick.
    <div class="col-md-6 col-xl-6 col-sm-6">
        <ul>
          <li id = "l1">name1</li>
          <li id = "l2">name2</li>
          <li id = "l3">name3</li>
          <li id = "l4">name4</li>
        </ul>
    </div>
    

    I am trying to read id of each

  • element inside onClick event using @Viewchild in the class but no value is coming in console.log();
     @ViewChild('li', {read: ViewContainerRef}) showAllData;
    
     @HostListener("click") onClick(){
          console.log( $(this.showAllData.nativeElement).attr('id'));
     }
    
  • Sumithra N
    • 93
    • 2
    • 6
    • Since you want just an eventListener, maybe this answer might help you https://stackoverflow.com/a/41610950/8437694 – IvanS95 Apr 09 '20 at 16:05
    • See this .. https://stackoverflow.com/questions/41700724/angular2-hostlistener-how-can-i-target-an-element-can-i-target-based-on-class – M A Salman Apr 09 '20 at 16:14
    • Try to avoid using jquery . this.showAllData.nativeElement.getAttribute("id") instead of $(this.showAllData.nativeElement).attr('id') – M A Salman Apr 09 '20 at 16:15
    • you can also `
    • name1
    • ` and forget use @HostListener – Eliseo Apr 09 '20 at 17:05
  • Thank you @Eliseo. It works. – Sumithra N Apr 09 '20 at 17:32