For displaying an HTML from an external URL, you can do the following steps.

  1. Declare DomSanitizer and HttpClient in your constructor.
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}

      2. Get the HTML from your URL as a response using the httpClient module.

this.http.get(“url”, {responseType: “text”}).subscribe(response => {
    this.displayHTML = this.sanitizer.bypassSecurityTrustHtml(response);
})

     3. Assign the displayHTML to the innerHTML property of your div element.

<div [innerHTML]=”displayHTML”></div>

Alternatively, you can also create a pipe for sanitizing the HTML if you are using the external URL at multiple places.

import { Pipe, PipeTransform } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser'; 

@Pipe({name: 'safeHtml'}) 
export class SafeHtml implements PipeTransform { 
    constructor(private sanitizer:DomSanitizer){} 
    
transform(html) { 
return this.sanitizer.bypassSecurityTrustStyle(html); 
} 
}

On the HTML side, use this pipe to sanitize your HTML.

<div [innerHTML]=”displayHTML | safeHtml”></div>

 

Support On Demand!

Angular