如何从innerHTML

时间:2017-08-27 11:32:29

标签: css angular innerhtml

我有管道:

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

我明白了:

  

&#34;警告:清理HTML会删除一些内容(请参阅http://g.co/ng/security#xss)。&#34;

3 个答案:

答案 0 :(得分:3)

如果没有 <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#0000ff" /> </shape> </item> <item android:bottom="10dp" android:top="10dp" > <shape android:shape="rectangle"> <solid android:color="#FFFF" /> </shape> </item> </layer-list> ,则无法使用

[innerHTML],否则会引发安全性错误。您可以在自定义管道中使用 DOMSanitizer provider 来清理HTML,如下所示,

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

答案 1 :(得分:1)

https://plnkr.co/edit/p0hsn57WT9FfO6E6lRjL?p=info&lt; - plunkr

将组件的视图封装模式设置为“无”,以使硬编码类在组件中工作

import { ViewEncapsulation } from '@angular/core'
装饰器中的

selector: 'your-component',
encapsulation: ViewEncapsulation.None, 

然后在返回之前清理管道中的HTML

export class SpanPipe implements PipeTransform 
{
    constructor(private sanitized: DomSanitizer) {}

    transform(value: string): any {
       return this.sanitized.bypassSecurityTrustHtml("<span class='mark'>xxx</div>"+value); 
    }
}

答案 2 :(得分:0)

修改

很抱歉..当你要插入新的html标签时,你必须使用DOMSanitizer

我附上了plunker来展示如何正确使用它

https://plnkr.co/edit/vBnF9hPSpw46053FQ08G?p=preview

您可以使用ngStyle

Pipes transform函数获取两个参数:&#39; value&#39;和&#39; args&#39;:

export interface PipeTransform {
    transform(value: any, ...args: any[]): any;
}

所以你可以传递你的管道参数。在这种情况下,我传递了字符串&#39; red&#39; (女巫很容易变成......)并在变换函数中使用它。

html的:

<div [innerHTML]="movie.title| spaning :'red'"></div>

.TS

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
   name: 'spaning',
   pure: false
})
export class SpanPipe implements PipeTransform 
{
transform(value: string,color:any): string
    {
        return this.sanitizer.bypassSecurityTrustHtml("<span class='mark' style=color:"+color+">xxx "+value+"</div>");
    }
}