As a project requirement, we have to load HTML content with CSS (in JSON response) from the backend dynamically and compile it in an Angular application. We also need to support those Angular directives defined in HTML. This article will describe the solution for both AngularJS and Angular.
AngularJS
To compile dynamical HTML in AngularJS, we just need to simply inject $compile
and use it to compile the HTML after injecting. So here we use a JQuery function to fetch HTML elements and set HTML into it.
sample1.json
And define directive like below,
Angular 10+
Now, let’s talk about implementation on Angular. The codes list below run under Angular 10.
To compile dynamical HTML, we need to install package @angular/platform-browser-dynamic
to install the JIT compiler manually.
app.module.ts
Then in the parent component which wants to create a sub-component and show/compile dynamical HTML. In component, we create a sub-component and put HTML and CSS data in it, and cast it to dynamicalComponent
.
dynamic-component.service:
Then we can define dynamicalComponent
with functions:
It should be noticed when a module is created dynamically ‘declarations: [componentType, directive1, directive2],’ ‘directive1,’ ‘directive2’ are included. That is how while dynamical HTML compiled, those predefined directives embedded in HTML can be triggered. For example: directive1
See demo: https://github.com/unicorn82/angular-dynamic-html-component