Appending HTML snippet to the view in Angular 6

杀马特。学长 韩版系。学妹 提交于 2019-12-30 11:44:18

问题


I am getting a piece of html code from a http request to an external system , and I should show this on my view in my angular app

to be percise this is the html snippet that I have to show (it will be a bit different by every request and response )

<div 
  id='paysonContainer'
  url='https://test-www.payson.se/embedded/checkout?id=af1ebee5-40bd-410a-90d1-a94401553414'>
</div>

<script 
  type='text/javascript' 
  src='https://test-www.payson.se/embedded/Content/payson.js?v2'>
</script>

I used different solution suggestions like innerHtml , but non of them is working for me (maybe because I have some script tag in my html code)

I am getting the html snippet as an string to a component and want to append it to the view (for example to a div in the view)


回答1:


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.




回答2:


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>') ;
  }


来源:https://stackoverflow.com/questions/51980322/appending-html-snippet-to-the-view-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!