Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class of specific parent Element in angular 2 on click anchor tag?

Tags:

angular

I am using like this in my HTML file:

       <div class="component" >
           <div class="component-header"  >
              <a href="javascript:" (click)="onClick($event)" >
                <i class="fa fa-chevron-right"></i>
                <i class="fa fa-chevron-left"></i>
              </a>
           </div>
      </div>

And in my JS file getting the class as:

onClick(event) {
    var target = event.target;
    var pElement = target.parentElement.parentElement;
    var pclassAttr = pElement.attributes.class;
    console.log(pclassAttr);
  }

Actually some time it consider that I’m clicking on the anchor and console class is "component" and some times it consider that I’m clicking on the "fa fa-chevron-right" and console class "component-header".

I need always console class as "component" when click on anchor.

Is there any thing wrong please suggest.

like image 799
Sagar Arora Avatar asked Dec 19 '22 10:12

Sagar Arora


1 Answers

Just use currentTarget instead of target. It will always be your anchor element because

currentTarget always refers to the element to which the event handler has been attached:

onClick(event) {
  var target = event.currentTarget;

  var pElement = target.parentElement.parentElement;
  var pclassAttr = pElement.attributes.class;
  console.log(pclassAttr);
}

See also

  • https://developer.mozilla.org/en/docs/Web/API/Event/currentTarget
like image 51
yurzui Avatar answered Jan 18 '23 22:01

yurzui