Here is a minimalistic example of a component
export class AppComponent {
htmlSnippet: string;
constructor(private sanitizer: DomSanitizer) {
this.htmlSnippet = this.sanitizer.sanitize(
SecurityContext.HTML,
`<p>snippet works!</p><script>alert("ddd");</script>`
);
}
}
and template
<p>app works!</p>
<div [innerHTML]="htmlSnippet"></div>
All the content is rendered. CSS works as well if any.

Is there a way to execute that alert?
you can just create the script tag and append that to the body of the component
constructor(private renderer2: Renderer2, private el: ElementRef) {}
ngAfterViewInit() {
let scriptEl = document.createElement("script");
scriptEl.innerText = "alert('hello')";
this.renderer2.appendChild(this.el.nativeElement, scriptEl);
}
demo 🚀
according to this issue you can't put a script tag in the body of the template because it going to be removed the only way around this is to insert the script tag dynamically as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With