使用Angular 2+ [innerHTML]添加包括样式属性的html [英] Using Angular 2+ [innerHTML] to add html including style attributes
问题描述
我正在使用Angular 2+ [innerHTML]输入来插入包括样式标签的HTML格式.
I'm using Angular 2+ [innerHTML] input to insert HTML formatting including style tags.
在我的模板中,我有类似的东西:
In my template I have something like:
<span [innerHTML]="someVar"></span>
在我的组件中,我有:
someVar = `<span style="background-color:#990000">test</span>`;
我收到警告:
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
在输出中,插入的跨度保持不变,减去style属性.
In the output, the inserted span in intact, minus the style attribute.
所以我使用了这篇文章中的管道:
So I used a pipe from this post:
https://stackoverflow.com/questions/37076867/
它看起来像:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({name: 'safeHtml'})
export class SanitizeHtml implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(html): SafeHtml {
// return this.sanitizer.bypassSecurityTrustStyle(style);
return this.sanitizer.bypassSecurityTrustHtml(html);
// return this.sanitizer.bypassSecurityTrustScript(value);
// return this.sanitizer.bypassSecurityTrustUrl(value);
// return this.sanitizer.bypassSecurityTrustResourceUrl(value);
}
}
这与以前没有什么区别,尽管我不确定我使用的是正确的方式...
This yields no difference than before, though I'm not sure I'm using that the right way...
如何使用innerHTML让Angular保留样式属性?
How can I get Angular to retain my style attribute using innerHTML?
推荐答案
您快到了.您只需要确保将HTML字符串用于管道即可.
You're nearly there. You just need to make sure that you are using your pipe for your HTML string.
示例管道:
import {Pipe} from '@angular/core';
import {DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe {
constructor(protected sanitizer: DomSanitizer) {}
transform(htmlString: string): any {
return this.sanitizer.bypassSecurityTrustHtml(htmlString);
}
}
示例用法:
<span [innerHTML]="someVar | safe"></span>
希望这会有所帮助!
这篇关于使用Angular 2+ [innerHTML]添加包括样式属性的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!