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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • DZone's Article Submission Guidelines
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Integration Isn’t a Task — It’s an Architectural Discipline
  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 user avatar
Eason YIN
·
Feb. 26, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
9.0K Views

Join the DZone community and get the full member experience.

Join For Free

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?
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!