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

24.6k views Asked by At

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!

4

There are 4 answers

0
Pankaj Parkar On

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>
1
micronyks On

You can use $event object as below:

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

stopPropagation(event: Event){
    event.stopPropagation();
    ...
}
0
yurzui On

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.

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.

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

0
Himanshu Patni On

(click)="$event.stopPropagation()" worked for me, earlier i was trying without "$" it was not working at that time.