简体   繁体   中英

Angular - How do I stop an anchor click from happening when someone clicks on a nested button

I have a div which shows a user notification in my Angular application.

The div is surrounded by an anchor tag which when clicked calls a function that marks the notification as read.

Separately the div contains a button which allows the user to go to the source of the notification.

My question is - when the user clicks on the button, how can I stop the anchor that marks the notification as read to be triggered as well?

<a (click)="toggleNotificationRead()" >
    <div>
      <button (click)="goTo()" >
          Go To
      </button>  
    </div>
</a>

In my component:

goTo() {
  window.location.href = `${this.url}`
};

You need to set the button's type:

<a (click)="toggleNotificationRead()" >
    <div>
      <button type="button" (click)="goTo()" >
          Go To
      </button>  
    </div>
</a>

additionally, you may need to catch the event and stop propagation, but you shouldn't need to do that:

<a (click)="toggleNotificationRead()" >
    <div>
      <button type="button" (click)="goTo($event)" >
          Go To
      </button>  
    </div>
</a>

goTo(event: Event) {
  event.stopPropagation();
  window.location.href = `${this.url}`
};

as a side note, this HTML isn't valid. You have block-level elements inside of inline elements. I would seriously consider restructuring this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM