DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Building Enterprise Authentication with Angular, Spring Boot, SSO, and MFA
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity

Trending

  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Designing Frontend Applications for Failure, Not Just Success
  • 10 Best Practices for Managing Kubernetes at Scale
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Load and Compile Dynamical HTML in AngularJS

Load and Compile Dynamical HTML in AngularJS

We have to load HTML content with CSS from the backend dynamically and compile it in an Angular application. We also need to support Angular directives defined in HTML.

By 
Eason YIN
·
Feb. 26, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

JSON
 




x


 
1
"content": ""<body width=\"100%\" class=\"height100 body\">\n<a name=\"N10001\"></a>\n<table directive1 data-elename=\"dmodule\" width=\"100%\" border=\"0\" frame=\"all\">\n<tbody><tr>\n<td",
2
"css" : ".isDisabled { cursor: not-allowed; opacity: 0.5; text-decoration: none;pointer-events: none; } .deleted { background-position: 0px 0px }"


TypeScript
 




xxxxxxxxxx
1
11


 
1
$http.get("data/sample1.json").then(function (response) {
2
      var content = response.data;
3
      var cssContent = content.css;
4
      var htmlContent = content.content;
5
      $timeout(function () {
6
      var tabContentElem = $("#html-content");
7
      tabContentElem.html("<div><style>" + cssContent + "</style>" + htmlContent + "</div>").promise().done(function () { 
8
      $compile(tabContentElem.contents())($scope);     
9
      });
10
    },500);
11
})



And define directive like below,

TypeScript
 




xxxxxxxxxx
1
21


 
1
myapp.directive('directive1', function ($window) {
2
  return {
3
      restrict: 'A',
4
      scope: true,
5
      link: function (scope, element, attr) {
6
        //behavior in directive
7
      }
8
  };
9
})
10
.directive('directive2', function ($window) {
11
  return {
12
      restrict: 'C',
13
      scope: true,
14
      link: function (scope, element, attr) {
15
           //behavior in directive
16
           element.on('click', function() {
17
              
18
      });
19
 
          
20
  }
21
};



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.

JSON
 




xxxxxxxxxx
1


 
1
"dependencies": {
2
    "@angular/animations": "~10.0.3",
3
    "@angular/common": "~10.0.3",
4
    "@angular/compiler": "~10.0.3",
5
    "@angular/core": "~10.0.3",
6
    "@angular/forms": "~10.0.3",
7
    "@angular/platform-browser": "~10.0.3",
8
    "@angular/platform-browser-dynamic": "^10.0.14",



app.module.ts

TypeScript
 




xxxxxxxxxx
1
14


 
1
import { NgModule, COMPILER_OPTIONS, CompilerFactory, Compiler} from '@angular/core'; 
2
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';
3
 
          
4
providers: [
5
    { provide: COMPILER_OPTIONS, useValue: {}, multi: true },
6
    { provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS] },
7
    { provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory] },
8
    ...
9
  ],
10
...
11
export class AppModule { }
12
export function createCompiler(compilerFactory: CompilerFactory): any{
13
  return compilerFactory.createCompiler();
14
}



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.

TypeScript
 




xxxxxxxxxx
1
17


 
1
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
2
private async generateUserDynamicComponent() {
3
    //  Define the component using Component decorator.
4
    const component = Component({
5
      template: this.htmlData,
6
      styles: [this.cssData]
7
    })(dynamicalComponent);
8
 
          
9
 
          
10
    const componentFactory = await this.dynamicComponentService.generateDynamic(component);
11
    //  Create the component and add to the view.
12
    const componentRef = this.container.createComponent(componentFactory);
13
    // Assign the service to the component instance
14
    componentRef.instance.dataService = this.dataService;
15
    this.dynamicComponent = componentRef;
16
    this.container.insert(componentRef.hostView);
17
  }


HTML
 




x


 
1
 
          
2
 
          
3
<ng-container #container>
4
</ng-container>



dynamic-component.service:

TypeScript
 




xxxxxxxxxx
1
27


 
1
async generateDynamic(component: any): Promise<ComponentFactory<any>> {
2
    this.compiler.clearCache();
3
 
          
4
    const type = component;
5
    const module = this.generateNewModule(type);
6
 
          
7
    return new Promise(
8
      (resolve, reject) => {
9
        this.compiler.compileModuleAndAllComponentsAsync(module)
10
          .then((factories) => {
11
            const componentFactory = factories.componentFactories[0];
12
            resolve(componentFactory);
13
          },
14
            (error) => reject(error));
15
      });
16
 
          
17
  }
18
 
          
19
  private generateNewModule(componentType: any): any {
20
    // Define the module using NgModule decorator.
21
    const module = NgModule({
22
      declarations: [componentType, directive1, directive2],
23
      imports: [CommonModule],
24
    })(class { });
25
 
          
26
    return module;
27
  }



Then we can define dynamicalComponent with functions:

TypeScript
 




xxxxxxxxxx
1
13


 
1
import { Directive, OnDestroy, OnInit, ViewChild } from '@angular/core';
2
 
          
3
@Directive({
4
  selector: 'dynamic'
5
}
6
 
          
7
constructor() { }
8
 
          
9
ngOnInit() {}
10
 
          
11
ngOnDestroy() {
12
   console.log('Dynamic Component OnDestroy')
13
}



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

TypeScript
 




xxxxxxxxxx
1
18


 
1
@Directive({
2
  selector: '[directive1]'
3
})
4
export class DynamicDirective1 {
5
 
          
6
  el: ElementRef;
7
 
          
8
  constructor(el: ElementRef) {
9
    this.el = el;
10
   }
11
 
          
12
  @HostBinding('class')
13
  elementClass = 'newclass';
14
 
          
15
  @HostListener('click', ['$event.target'])
16
  onClick(): void {
17
    ...
18
 }



See demo: https://github.com/unicorn82/angular-dynamic-html-component

HTML AngularJS

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Building Enterprise Authentication with Angular, Spring Boot, SSO, and MFA
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook