typescript Angular 2:单击链接时停止传播父元素的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41530904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 : Stop propagation of parent element's event , when clicking on link
提问by misha
I have a case of event bubbling. Example :
我有一个事件冒泡的情况。例子 :
<td (click)="doSomething()">
<text [innerHtml]="content">
// content of innerHtml is : <a href="http://google.com"></a>
</text>
</td>
The tag is rendered from another component through innerHtml. The problem: when i click on the link, the click event of element is fired also. How to solve the problem (stop the propagation of doSomething()), knowing that event handlers(or any angular 2 code ) can't be passed through innerHtml?
标签是通过innerHtml从另一个组件渲染的。问题:当我点击链接时,元素的点击事件也会被触发。如何解决问题(停止 doSomething() 的传播),知道事件处理程序(或任何 angular 2 代码)不能通过 innerHtml 传递?
Thank you!
谢谢!
回答by Pankaj Parkar
Workaroundcould be simply placing (click)="$event.stopPropagation()"
over text
component, so that event will not get bubbled up from hosting component. Same thing can be improvise by writing a Directive
.
解决方法可以简单地放置(click)="$event.stopPropagation()"
在text
组件上,这样事件就不会从托管组件中冒出来。同样的事情可以通过编写一个Directive
.
<td (click)="doSomething()">
<text (click)="$event.stopPropagation()" [innerHtml]="content">
// content of innerHtml is : <a href="http://google.com"></a>
</text>
</td>
回答by yurzui
You can take advantage of bubbling. From your handler you can look at event.target
to see if an A
was clicked, and if so, skip your action.
您可以利用冒泡。从您的处理程序中,您可以event.target
查看是否A
点击了一个,如果是,请跳过您的操作。
Be careful, though, because event.target
may be the SPAN
! You need to not just check if the event's target is an A
tag, but also walk up the DOM tree in a simple simulation of bubbling.
不过要小心,因为event.target
可能是SPAN
! 您不仅需要检查事件的目标是否是A
标签,还需要在冒泡的简单模拟中沿着 DOM 树向上走。
So here's possible solution:
所以这是可能的解决方案:
template
模板
(click)="doSomething($event)"
component
零件
export class AppComponent {
content = '<a href="http://google.com">Link text <span>Nested text</span></a>'
doSomething(e) {
let target = e.target;
while (target !== e.currentTarget) {
if (target.tagName == 'A') return;
target = target.parentNode;
}
alert('do something')
}
}
回答by micronyks
You can use $event
object as below:
您可以使用$event
对象如下:
<a (click)="stopPropagation($event);false" //<<<----added click event
href="http://google.com">
</a>
stopPropagation(event: Event){
event.stopPropagation();
...
}