Angular 2: stop propagating parent event when clicking on link

I have a case of bubbling events. Example:

<td (click)="doSomething()"> <text [innerHtml]="content"> // content of innerHtml is : <a href="http://google.com"></a> </text> </td> 

The tag is passed from another component via innerHtml. Problem: when I click on the link, the click event of the element is fired. How to solve the problem (stop distributing doSomething ()), knowing that event handlers (or any angular 2 code) cannot be passed through innerHtml?

Thanks!

+11
source share
3 answers

A workaround can simply place the component (click)="$event.stopPropagation()" on top of the text so that the event does not receive bubbles from the hosting component. You can improvise the same by writing Directive .

 <td (click)="doSomething()"> <text (click)="$event.stopPropagation()" [innerHtml]="content"> // content of innerHtml is : <a href="http://google.com"></a> </text> </td> 
+17
source

You can use the bubbles. From your handler, you can look at event.target to see if A was pressed, and if so, skip the action.

Be careful because event.target may be SPAN ! You need to not only check if the event target is an A tag, but also go to the DOM tree in a simple bubble simulation.

So this is a 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') } } 

Plunger example

+7
source

You can use the $event object as shown below:

 <a (click)="stopPropagation($event);false" //<<<----added click event href="http://google.com"> </a> stopPropagation(event: Event){ event.stopPropagation(); ... } 
+4
source

Source: https://habr.com/ru/post/1013872/


All Articles