1

I have to enter some html via typescript using the [innerHTML] tag on the template.

I am trying to put a click function on the html:

status = "<img src='assets/hello.png' (click)='hello()' />";

But the click function gets stripped away with the console saying:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

I see a few people have mentioned using "DomSanitizer" but can't find an example which fixes my exact problem.

Andrew Junior Howard
  • 2,427
  • 4
  • 29
  • 45

1 Answers1

7

Angular is stripping out everything Angular specific if you are using [innerHTML].

If you need something like that, you can create components at runtime like explained in Equivalent of $compile in Angular 2
or you can use imperative code to add an event handler like

constructor(private elRef:ElementRef, private cdRef:ChangeDetectorRef) {}

someMethod() {
  this.status = "<img src='assets/hello.png' (click)='hello()' />";
  this.cdRef.detectChanges();
  this.elRef.nativeElement.querySelector('img').addEventListener('click', this.hello.bind(this);
}
Community
  • 1
  • 1
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506