将HTML代码段追加到Angular 6中的视图 [英] Appending HTML snippet to the view in Angular 6

查看:111
本文介绍了将HTML代码段追加到Angular 6中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从http请求到外部系统都得到了一段html代码,应该在我的角度应用程序中的视图中显示它

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

准确地说,这是我必须显示的html代码段(每个请求和响应都会有所不同)

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>

我使用了诸如innerHtml之类的不同解决方案建议,但是其中没有一个对我有用(也许是因为我的html代码中有一些脚本标签)

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)

我正在将html代码段作为字符串添加到组件,并希望将其附加到视图(例如,添加到视图中的div)

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)

推荐答案

此脚本可以包装在div中吗?

Can this script be wrapped in a div?

如果是,则只需对空的div使用[innerHTML]属性绑定语法,并使用str作为其值.

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.

在模板中,您可以简单地将str用作:

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

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

我能够在用户界面上看到该div中的任何内容.

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

即使 Angular Documentation 也是如此.

绕过安全性并信任给定的值是安全的HTML.仅在绑定的HTML不安全(例如包含标签)并且应执行代码时才使用此功能.清理程序将保留安全的HTML,因此在大多数情况下,不应使用此方法.

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.

这篇关于将HTML代码段追加到Angular 6中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆