19

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!

misha
  • 231
  • 1
  • 2
  • 5

4 Answers4

31

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
9

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
6

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();
    ...
}
Christopher
  • 856
  • 9
  • 16
micronyks
  • 54,797
  • 15
  • 112
  • 146
1

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