Angular 4 | iframe to be populated in innerHTML

2020-04-21 01:46发布

问题:

I have a problem

I have subscribed to API which returns some HTML content. sometimes it has iframes. however, only the iframe is not loading and instead it is showing as a string in the browser. Please check below code

Component File

this._EmittersService.longDescemitted$.subscribe(obj => {
  this.longDesc = obj;
 });`

html file

<div class="description-panel" [innerHTML]="longDesc" ></div>

Problem: when the

this.longDesc = "<iframe width="something" height="something" src="something" ></iframe>"

this is displayed as a string, it is not detecting it has an iframe. I NEED the angular to allow it to be rendered as HTML.

回答1:

Step1 : Import the below part in ts file

import {DomSanitizer} from '@angular/platform-browser';

Step 2 :Define constructor in perticular ts file

constructor(private domSanitizer:DomSanitizer) {}

Step 3:-Use below code in ts file according to requirement (method/ function or constructor)

this._EmittersService.longDescemitted$.subscribe(obj => {
      this.longDesc = this.domSanitizer.bypassSecurityTrustHtml(obj or any html content);
or 
this.longDesc = this.domSanitizer.bypassSecurityTrustHtml('<iframe width="something" height="something" src="something" ></iframe>')
     });