我有 pipe :
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'spaning',
pure: false
})
export class SpanPipe implements PipeTransform
{
transform(value: string): string
{
return "<span class='mark'>xxx</div>"+value;
}
}
然后像这样使用它:
<div [innerHTML]="movie.title| spaning"></div>
如何在 css 中设置 .mark 类的样式?我希望 xxx 变成红色。我对解决方法不感兴趣,类必须添加到管道中,如上所述。
答案与 Angular 2 - innerHTML styling ,但我自己找不到解决方案。
如果我只是在我使用此管道的组件中添加样式:
.mark{
color: red;
}
我得到:
"WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss)."
最佳答案
[innerHTML]
不能在没有 DOMSanitizer provider
的情况下使用,否则会引发安全错误。您可以在自定义管道中使用 DOMSanitizer provider
来清理您的 HTML,如下所示,
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
@Pipe({
name: 'spaning',
pure: false
})
export class SpanPipe implements PipeTransform
{
constructor(private sanitized: DomSanitizer) {}
transform(value: string,color:any): SafeHtml{
return this.sanitized.bypassSecurityTrustHtml("<span class='mark' [ngStyle]="{'color':color}">xxx</div>"+value);
}
}
HTML
<div [innerHTML]="movie.title| spaning :'red'"></div>
关于css - 如何从 innerHTML 应用 CSS .class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904496/