【问题标题】:Render Html from JSON without displaying content of style tag in Angular 4从 JSON 渲染 Html 而不在 Angular 4 中显示样式标签的内容
【发布时间】:2017-10-01 19:27:22
【问题描述】:

我的 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;} 苹果 iPhone 6 金色,128 GB 全新

样式标签的内容上方不应显示。

请帮我一个办法让它工作。

【问题讨论】:

    标签: javascript json angular


    【解决方案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,对字符串进行拆分操作,得到你想要的文本:

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

    【讨论】:

    • 如果你想拥有风格,你可以从字符串中获取风格并用 [NgStyle] 注入它。
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 2013-10-29
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2017-11-29
    相关资源
    最近更新 更多