3

I get from my API a whole HTML-page as a string, containing css (inline as well as in header) and javascript, looking like this:

<script></script>
<style></style>
<div></div>
.
.
.
</html>

There are no external files, so just a complete HTML page.

I tried to set the document.innerHtml via a function to the string content, HTML is working more or less in this case, but script parts are obv. ignored.

I also tried to just set the template of a component to the string, but then I get a lot of errors, e.G. Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) (because of the containing js I expect) and a lot of Unexpected closing tag "span". It may happen when the tag has already been closed by another tag. (read about this one, I just want angular to don´t touch my string)

In another try, I just created a template with one div, that is then filled by the string. Didn´t work because of sanitation, after adding a bypassSecurityTrustHtml, it worked but the css is completly messed up and all js is just removed.

I know that it´s not the angular way to work, but we have a running software that needs to be migrated to angular and pages are generated by a python engine so I don´t have a real way to change the string before I get it from the api. If there would be a way to read the parts, css, scripts out of the string and somehow seperatly pass them to the page I would also be content (as long as it doesn´t cost to much performance)

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Mesman
  • 33
  • 3

1 Answers1

1

I would split the problem into two sections, appending the html and css and then adding the javascript.

  • First, load the script.

As stated, you are receiving the whole content has a string. Since you know that the javascript will be between the <script>...</script> tags, you can get it usuing regex or other ways. Once you have the script url you can load it by following this stackoverflow or others.

There are several ways to append scripts that can be used in Angular, that stackoverflow contains lots of them.

  • Second, create the DOM element from the HTML and CSS string

Similarly to previous, you can extract the HTML and css code. Once done, you can use the DOMParser Api to convert your string to a proper DOM element.

  • Third, use the Renderer2 to add the created DOM element

Angular allows the manipulation of DOM elements of an application in a safe way. This is done with the Renderer2 API. In particular the appendChild method allows you to add a DOM element to any other DOM element that you want. You can use this API to add the content that you received.

IDK4real
  • 757
  • 6
  • 14