0

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.

Dhaneja
  • 27
  • 8

1 Answers1

0

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>',
    );
piedpiper
  • 520
  • 5
  • 18
  • I am bringing a string to the front end not an URL. I need to combine both Html and CSS strings together. Not display just one. Is there any chance of doing that? Thanks for your comment. @piedpiper – Dhaneja May 08 '21 at 14:26
  • can you share the value of `mypreview`.then it would be easier tounderstand. – piedpiper May 08 '21 at 18:53
  • mypreview contains a string of html code. Something like My document in here. Its pretty long that is why I mentioned this sample. It also consists with inline CSS. Now what I want to do is to add an external CSS string(similar to the html string "mypreview") to the iframe or whatever possible method. Thanks for your answer – Dhaneja May 09 '21 at 02:38
  • In that case i have updated the answer. maybe you can try that. – piedpiper May 09 '21 at 07:31