Appending HTML snippet to the view in Angular 6

若如初见. 提交于 2019-12-01 09:38:49

Can this script be wrapped in a div?

If yes, then simply use the [innerHTML] property binding syntax on an empty div and use the str as it's value.

After doing that though, you're going to get an unsafe scripts error which you can fix by passing it through the sanitize pipe that you can create like this:

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

@Pipe({
  name: 'sanitize'
})
export class SanitizePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  transform(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

Creating a Pipe will help you reuse this logic at several places in your App.

And in your template, you can simply use the str as:

<div [innerHTML]="str | sanitize">
</div>

I was able to see any content from this div on the UI.

Even the Angular Documentation says the same.

Bypass security and trust the given value to be safe HTML. Only use this when the bound HTML is unsafe (e.g. contains tags) and the code should be executed. The sanitizer will leave safe HTML intact, so in most situations this method should not be used.

You can try using DOMSanitizer class

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

constructor(private sanitizer: DomSanitizer) {
    this.html = sanitizer.bypassSecurityTrustHtml('<div 
  id='paysonContainer'
  url='https://test-www.payson.se/embedded/checkout?id=af1ebee5-40bd-410a-90d1-a94401553414'>
</div>') ;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!