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 Howard
  • 2,818
  • 5
  • 33
  • 59

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
  • 623,577
  • 216
  • 2,003
  • 1,567