AngularM
AngularM

Reputation: 16618

Angular2 stops (click) working when using DomSanitizer

I'm using Angular2 with typescript.

I have a pipe that works regarding rendering the HTML fine. Problem is the DomSanitizer seems to stop the (click) event from working.

When I check the HTML in the console.log (F12) the (click) code seems to be there and not stripped out.

But when I click the link it does nothing.

This is an example of the link (it calls a function in my component):

<a (click)="recordLinkClick()" target="_blank" href="#">Test link</a>

This is the pipe:

import { Pipe } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe {

  constructor(protected _sanitizer: DomSanitizer) {

  }

  public transform(value: string, type: string = 'html'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html': return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style': return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script': return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url': return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default: throw new Error(`Invalid safe type specified: ${type}`);
    }
  }

}

This is the line of HTML:

<div [innerHTML]="selectedArticle.body | safe: 'html'"></div>   

Let me know if you need to see anymore code.

Upvotes: 0

Views: 2475

Answers (1)

basarat
basarat

Reputation: 276161

<a (click)="recordLinkClick()" target="_blank" href="#">Test link</a>

If you want this anchor to be put in by innerHTML angular will not register it without you compiling the html before putting it into the DOM.

The steps for dynamically compiling html for angular 2 are covered here : How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Upvotes: 1

Related Questions