Add external HTML pages inside components


Difficulty

We may need to insert static or dynamic HTML pages / fragments coming from outside our website.
With this little trick we can make a “get” call for the HTML we need to show it in a <div> container.
The fragment must not have unexpected HTML (such as style or javascript attributes), because these parts will be “sanitized” (read “removed”) before rendering, with the following warning message in console:

WARNING: sanitizing HTML stripped some content

app.component.ts 💾

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  private myTemplate: any = '';

  constructor(private _http: HttpClient) {
    this._http.get<String>('/assets/page.html',
      {responseType: 'text'}).subscribe(html => this.myTemplate = html);
  }
}


app.component.html 💾

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

The fragment downloaded can be either a page on another domain or a page inside your domain, for example under “/ assets” directory. If the page is hosted on another domain, that domain must allow downloading for the CORS policy.

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.