我想让一个子元素触发它自己的点击,并且不要回复它有[routerLink]的父元素,问题是子元素可以'在delete()
中运行(click)="delete()"
函数,只需跟随[routerLink]
中的父项(它导航到/ product /:id)
<div class="item">
<!-- parent element -->
<a [routerLink]="['/product/'+product.id]">
<div class="figure">
<div class="sides">
<div class="side">
<div class="card">
<img class="img" [src]="product.thumb">
<div class="content">
<div class="header">{{product.name}}</div>
<div class="meta"> <span>product.category</span> </div>
</div>
<div class="extraContent"> <span class="ui right floated black">
<!-- child element -->
<a (click)="delete()" ><i class="red trash outline icon"></i></a></span> <span><i class="deleteProductIcon"></i></span> </div>
<!-- child element -->
</div>
</div>
</div>
</div>
</a>
<!-- parent element -->
</div>
我尝试将[routerLink]
移到上方div
,但它仍然采取相同的行为
答案 0 :(得分:4)
在您的情况下,仅指定stopPropagation的孩子有时可能无效。特别是当孩子和父母都有他们独立的&#34; routerLinks&#34;定义
我建议使用&#34;导航&#34;处理路由。组件中的方法并返回&#34; false&#34;到底。这将阻止父路由在完成子项的单击处理程序后触发。
// pass in the event object to the delete function
<a (click)="delete($event)" ><i class="red trash outline icon"></i></a>
// in the delete function, stop event propagation
delete(event){
event.stopPropagation();
this.route.navigate(['child/route/here']);
return false;
}
从点击处理程序返回false会阻止父路由为我工作。
答案 1 :(得分:2)
如果你在delete function()中停止播放,那么事件将不会通过routerLink冒泡到锚标记
// pass in the event object to the delete function
<a (click)="delete($event)" ><i class="red trash outline icon"></i></a>
// in the delete function, stop event propagation
delete(event){
event.stopPropagation();
}
答案 2 :(得分:0)
仅event.stopPropagation();
对我不起作用。我要做的就是也加入e.preventDefault();
// In your HTML
<a [routerLink]="['/product/'+product.id]">
<!-- your other inner stuff -->
<a (click)="delete($event)" ><i class="red trash outline icon"></i></a>
</a>
// In your component
delete(e){
e.stopPropagation();
e.preventDefault();
}