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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:08:54  来源:igfitidea点击:

Angular 2 : Stop propagation of parent element's event , when clicking on link

angulartypescriptinnerhtmlangular2-templateevent-bubbling

提问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 textcomponent, 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.targetto see if an Awas clicked, and if so, skip your action.

您可以利用冒泡。从您的处理程序中,您可以event.target查看是否A点击了一个,如果是,请跳过您的操作。

Be careful, though, because event.targetmay be the SPAN! You need to not just check if the event's target is an Atag, 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')
  }
}

Plunker Example

Plunker 示例

回答by micronyks

You can use $eventobject as below:

您可以使用$event对象如下:

<a (click)="stopPropagation($event);false"     //<<<----added click event
    href="http://google.com">
</a>

stopPropagation(event: Event){
    event.stopPropagation();
    ...
}