angular2 显示后端返回的html 安全转换

前端之家收集整理的这篇文章主要介绍了angular2 显示后端返回的html 安全转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、上传文件回显缩略图

<input type="file" name="fileUpload" [(ngModel)]="fileUpload"
 (change)="sendImg($event)"/>

sendImg(event) {
    let url = window.URL.createObjectURL(event.srcElement.files[0]);
}
// 获取到一个不安全的临时图片链接地址

2、在angular2中使用,定义管道,过滤

import { Pipe,PipeTransform,SecurityContext } from '@angular/core';
import { DomSanitizer,SafeHtml,SafeStyle,SafeScript,SafeUrl,SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
    name: 'safe'
})
export class SafePipe implements PipeTransform {
    constructor(protected dom: DomSanitizer) {}
    public transform(value: string,type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
                  case 'html':
                    return this.dom.bypassSecurityTrustHtml(value);
                  case 'style':
                    return this.dom.bypassSecurityTrustStyle(value);
                  case 'script':
                    return this.dom.bypassSecurityTrustScript(value);
                  case 'url':
                    return this.dom.bypassSecurityTrustUrl(value);
                  case 'resourceUrl':
                    return this.dom.bypassSecurityTrustResourceUrl(value);
                  default:
                    return value;
         }
    }
}

使用
<div [innerHTML]="html | safe:'html'"></div>

参考链接https://github.com/oppoffice/...

猜你在找的Angularjs相关文章