How to display a html document with external stylesheet in iframe? Angular Html CSS

1.3k views Asked by At

My application front end uses Angular.

I am trying to display an html document (in my case a preview of a document generated using user input data). I can successfully display the Html and inline CSS within the document to an iframe. But I cannot find a method to include the external style sheet to the same iframe.

Is there any method which I can use in the angular file to integrate the external CSS file with the html I have successfully passed into the iframe.

I am currently using

<iframe [srcdoc] = "mypreview" ></iframe>

"mypreviw" is the html string which I brought from the backend

I used DOM sanitizer to sanitize the html string as well. I can bring the Styles string in similar method. But Please let me know if there is any method to integrate these 2 strings to the iframe.

Any solution other than or similar to iframe would be also fine. I need a good preview of my doc that's it

Thank You.

1

There are 1 answers

4
piedpiper On BEST ANSWER

You can use domsanitizer for external sources.

import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'yourapp',
  templateUrl: './yourapp.component.html',
  styleUrls: ['./yourapp.component.scss']
})

export class YourApp implements OnInit {
  @Input()
  url: string = "https://www.example.com";
  mypreview: SafeResourceUrl;

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.mypreview= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
  }

}

after the dom sanitization you can use that variable in iframe

<iframe width="100%" height="100%" frameBorder="0" [src]="mypreview"></iframe>

In case you want to show html in iframe you can try this

<div [innerHTML]="mypreview"></div>

inside that bypassSecurityTrustHtml will help

this.mypreview= this.sanitizer.bypassSecurityTrustHtml(
      '<iframe width="100%" height="800" src="https://primefaces.org/primeng/#/"></iframe>',
    );