简体   繁体   中英

Setting iframe src attribute in Angular

I am trying to show a preview of the HTML code typed into textarea when a preview button is clicked through iframe.

I have attempted to use the setAttribute function of Renderer2 but keep getting a

ERROR TypeError: Cannot read properties of undefined (reading 'setAttribute')

Below is the relevant code.

HTML

<div class="wrap">
<textarea #postform id="postform" [(ngModel)]="this.display[0].MDFile" class="textarea_MD" style="overflow: hidden; overflow-wrap: break-word; height: 550px; width:600px; " placeholder="Enter markdown here"></textarea>
<br>
<br>
<button class="btn" (click)="saveMD()">Save</button>
<p></p>
<button class="btn" (click)="previewHTML()">Preview HTML</button>
<button class="btn" (click)="toDashboard()">Dashboard</button>
</div>
<iframe srcdoc="" class="preview" title="Preview"></iframe>

Component.ts

  previewHTML(): void {
    let html: any = this.domSanitizer.bypassSecurityTrustHtml(this.display[0].MDFile);
    this.renderer.setAttribute(this.preview.nativeElement, 'src','data:text/html;charset=utf-8,' + encodeURI(html));
  }

this.display[0].MDFile is where the HTML content/text is saved by a two-way binding NgModel.

What could be the cause of the TypeError and could there be a way to resolve this?

If not, any advice on achieving the HTML preview would be appreciated.

Thanks in advance.

Turns out didn't even need to use Renderer2.

Changed the code to:

HTML

<iframe [src]='html' class="preview" title="Preview"></iframe>

Component.ts

previewHTML(): void {
    let file ='data:text/html;charset=utf-8,' + encodeURI(this.display[0].MDFile);
    this.html = this.domSanitizer.bypassSecurityTrustResourceUrl(file);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM