[英]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. 我有一个div,它在Angular应用程序中显示用户通知。
The div is surrounded by an anchor tag which when clicked calls a function that marks the notification as read. div被锚标记包围,单击该锚标记将调用一个将通知标记为已读的函数。
Separately the div contains a button which allows the user to go to the source of the notification. div单独包含一个按钮,该按钮使用户可以转到通知源。
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. 附带说明,此HTML无效。 You have block-level elements inside of inline elements. 内联元素中有块级元素。 I would seriously consider restructuring this code. 我将认真考虑重组此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.