How can I execute a script in the innerHtml of an HTML element. I have a string of HTML with a script element included, like the HTML sample below.
<strong>asdasd</strong><br>
<p>asdasd</p>
<script>alert('aa')</script>
I have tried to inject this HTML into my component, with the following HTML code in my component's template.
<div [innerHTML]="customScript"></div>
My problem is that the script in the HTML string does not run. How can I make the contents of the script element embedded in the innerHTML of the div element execute?
In the second code snippet, the customScript variable isn't hard-coded anywhere. It is a string that comes from the back-end. It can contain any tag like html, body, div, script (Yes! Script needs to be allowed!). I need to make any script in the customScript HTML string run in my component as normal html/script code.
customScriptis hardcoded, you could just call the alert in a lifecycle method.<script>intodocument.head. Also, never usealert. We've had the console API since 2010, use it.