Why Angular2 (click) event is not firing on a <div>?

80,975

Solution 1

Your code snippet looks all good!

The issue is in your CSS styles. Your <div> probably either inherits a different position value or simply - goes behind another element which element blocks your <div> (does not allow it to be clicked).

By changing the position to relative it works, most probably because this position enables z-index and moves your <div> on top to the other element that's blocking it.

This should be enough for you to figure it out. But if you want more detailed answer - please share your CSS too.

Solution 2

Faced the same issue, and the problem was that I named an HTML element and the method the same.

It was such:

mycomponent.html

<div #doSomething>
</div>

<div (click)="doSomething();">
</div>

mycomponent.ts

doSomething() {
    // ...
}

Solution 3

I was also facing the similar issue mostly time on Iphone. basically the pointer-event causing the stuck on the components. So I just applied the below fix at all the events where i applied the (click) property on the tag.

    a,
    div,
    ion-item,
    .item-md,
    .item-ios,
    .segment-button,
    .select-md
    .select-ios,
    .button-ios,
    .button-md,
    .searchbar-md,
    .searchbar-ios {
        pointer-events: auto !important;
    }

Now it is working fine in both Android and IOS platform.

Share:
80,975

Related videos on Youtube

Ziv
Author by

Ziv

Updated on May 15, 2022

Comments

  • Ziv
    Ziv 13 days

    I found a strange behaviour with Angular2:

    (click) isn't firing on this:

    <div (click)="test()">test</div>
    

    But it works here:

    <div style="position: relative;" (click)="test()">test</div>
    

    Can anyone explain this behaviour? Why there is a need to set position style in order for (click) to fire?

    Am I missing anything?

    • eko
      eko over 5 years
      Can you reproduce this issue on plunker?
    • yurzui
      yurzui over 5 years
      Please reproduce it. I'm pretty sure that problem is in your markup and styles
    • Aravind
      Aravind over 5 years
      where is your component.ts module declarations and so on. with one line of HTML nothing can be helped.
    • nativelectronic
      nativelectronic 10 months
      nowadays angular use stopropagation by default, and remember to put a id o key on the element selected
  • Ziv
    Ziv over 5 years
    Thanks. It is an issue with the css. I am using Angular-cli, on a fresh project all works fine. When I add bootstrap4 I see this behavior probably due to bootstrap's default css.
  • Frank Cannon
    Frank Cannon over 4 years
    I am getting the same issue with Angular 4 and Bootstrap 4.