从JSON渲染Html而不在Angular 4中显示样式标记的内容

时间:2017-10-01 19:27:22

标签: javascript json angular

我的JSON看起来像这样

{
    "product_details": {
        "description": "<style> img {width: 320px; height: auto;}</style>Apple iPhone 6 Gold , 128 GB New"
    }
}

我有一个类似的组件模板:

<div class="panel-body" [innerHTML]="product_detail.description"></div>

如果我试图在浏览器中呈现它,它就会显示如下。

img {width: 320px; height: auto;} Apple iPhone 6 Gold,128 GB新

不应显示样式标记内容之上的

请帮我一个方法来实现这一目标。

1 个答案:

答案 0 :(得分:1)

在Angular中,您可以使用自定义管道来过滤product_detail.description

这里是plunker of that method,请按照以下方式实施:

<div class="panel-body" [innerHTML]="product_detail.description | getUnstyledText"></div>

@Pipe({name: 'getUnstyledText'})
export class GetUnstyledTextPipe implements PipeTransform {
  transform(text: string): string {
    let splitArray = text.split('</style>');
    return splitArray[splitArray.length-1];
  }
}

上面的例子是实现这个普通的JS,对字符串进行拆分操作以获取所需的文本:

&#13;
&#13;
var string = "<style> img {width: 320px; height: auto;}</style>Apple iPhone 6 Gold , 128 GB New";

var splitString = string.split('</style>')

console.log(splitString[splitString.length-1]);
&#13;
&#13;
&#13;