htmlangularangular2-templateangular2-databinding

Inserting HTML (with angular 2 directives) from the server into the DOM


I have ~2,000 lines of HTML code that I can retrieve from my Java server. This HTML code also has angular directives inside of it, such as ngIf* and (click) and [ngClass]. When I try to display that HTML in my client with such methods as the below:

<div [innerHTML]="htmlData"></div>
<div innerHTML="{{ htmlData }}"></div>

I see all of the HTML elements displayed correctly, but none of the angular directives are working (such as some of the HTML should be hidden with the *ngIf but they aren't... and none of the (click) events work. What can I do to fix this?

I need this functionality because I am delivering my code as a JAR file to various users to run on their local machines, and I want to serve the HTML code from some Amazon's S3 so I can update it whenever I want to give their website an update.

And I tried looking at the below answers, but those dealt with pure HTML from the server, and didn't have any angular directives.

Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2)

Angular HTML binding


Solution

  • Unfortunately it's not possible. InnterHTML will put HTML code there - not angular. Angular code should be compiled ahead of time - a process where all the directives and html magic is replaced with simple JS.

    You can transform you angular code to plain html by server side rendering with node js.

    You can read more about server side rendering here: https://angular.io/guide/universal

    But just as well you can use JAVA and with any popular templating framework for JAVA servers if you'll send your parameters on the http request.