htmlangulartypescripthtml-templates

Angular2 include html from server into a div


I got a serie of html in my server. For example:

And I trying to include those files into a<div> in my angular2 v4 app. For example:

component.ts

public changePage(name: string) {
  switch (name) {
    case 'intro': this.myHtmlTemplate = 'http://docs.example.com/intro.html'; break;
    case 'page1': this.myHtmlTemplate = 'http://docs.example.com/page1.html'; break;
    case 'page2': this.myHtmlTemplate = 'http://docs.example.com/page2.html'; break;
  }
}

component.html

<div [innerHtml]="myHtmlTemplate"></div>

but it doesnt work. I tried the following solutions:

Angular4 Load external html page in a div

Dynamically load HTML template in angular2

but it doesn't work for me. Can somebody help me with this problem please ?


Solution

  • Angular security Blocks dynamic rendering of HTML and other scripts. You need to bypass them using DOM Sanitizer.

    Read more here : Angular Security

    DO below changes in your code :

    // in your component.ts file
    
    //import this 
    import { DomSanitizer } from '@angular/platform-browser';
    
    
    // in constructor create object 
    
    constructor( 
    ...
    private sanitizer: DomSanitizer
    
    ...
    ){
    
    }
    
    someMethod(){
    
      const headers = new HttpHeaders({
      'Content-Type':  'text/plain',
    });
    const request = this.http.get<string>('https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form', {
      headers: headers,
      responseType: 'text'
    }).subscribe(res => this.htmlString = res);
    
     this.htmlData = this.sanitizer.bypassSecurityTrustHtml(this.htmlString); // this line bypasses angular security
    
    }
    

    and in HTML file ;

    <!-- In Your html file-->
        <div [innerHtml]="htmlData">
        </div>
    

    Here is the working example of your requirement :

    Working Stackblitz Demo