Ziv
Ziv

Reputation: 568

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

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?

Upvotes: 53

Views: 112916

Answers (5)

huonggiang141806
huonggiang141806

Reputation: 11

I add a tag inside div tag

<div class="item" *ngFor="let item of curriculumArray">
    <a (click)="goToDetail(item.curriculumId)">
    <p class="p-title">{{ item.curriculumName }}</p>
    <p class="p-description">{{ item.description }}</p>
    <div class="icon-button">
      <img
        class="delete"
        title="Xóa chương trình"
        src="../../../assets/icon/delete_icon.png"
        alt="delete button"
      />
      <img
        class="edit"
        title="Chỉnh sửa chương trình"
        src="../../../assets/icon/edit_icon.png"
        alt="edit button"
      />
    </div>
    </a>
  </div>

Upvotes: 1

dada delos angeles
dada delos angeles

Reputation: 53

<div (click)="myFunction()"> 
<my-component></my-component>
</div>

^ this worked for me

Upvotes: 0

MMalke
MMalke

Reputation: 2106

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() {
    // ...
}

Upvotes: 5

Atif Hussain
Atif Hussain

Reputation: 898

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.

Upvotes: 1

Kaloyan Kosev
Kaloyan Kosev

Reputation: 13067

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.

Upvotes: 59

Related Questions