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.

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. I'm getting the error "Property 'querySelector' does not exist on type 'ElementRef'.
Sorry, I missed nativeElement.
Thanks. But if I was to pass an object to my 'hello' function I can't pass the object in via the string way can I?
What object? You can do ....addEventListener('click', (evt) => this.hello(evt, this.someObject);
Thanks :) I just tried it all but it says "EXCEPTION: Cannot read property 'addEventListener' of null"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.