Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

Thank you!

like image 795
misha Avatar asked Jan 08 '17 08:01

misha


People also ask

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

How will you prevent event from being propagated?

stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

How do you stop event propagation from parent to child?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.


Video Answer


1 Answers

Workaround could 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.

<td (click)="doSomething()">
  <text (click)="$event.stopPropagation()" [innerHtml]="content"> 
        //  content of innerHtml is :  <a href="http://google.com"></a>
  </text>
</td>
like image 173
Pankaj Parkar Avatar answered Sep 21 '22 19:09

Pankaj Parkar