Angular 5 - sanitizing HTML with pipe

烈酒焚心 提交于 2020-02-02 02:34:06

问题


When i got the warning:

"WARNING: sanitizing HTML stripped some content"

I did some research and saw people using the pipe below or a pipe that looks like the one below

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'sanitizeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

 constructor(private _sanitizer:DomSanitizer) { }

 transform(v:string):SafeHtml {
   return this._sanitizer.bypassSecurityTrustHtml(v);
 }
}

Unfortunately I still get the same error even when i implement the pipe like this:

<span [innerHTML]="specialist.blocks[0].paragraph.html | sanitizeHtml"></span>
<p [innerHTML]="package.fields.remarks | sanitizeHtml"></p>
<li [innerHTML]="package.fields.name | sanitizeHtml"></li>

So I'm wondering if I implemented the pipe wrong or is there something else why it doesn't work?

Edit:

example of specialist.blocks[0].paragraph.html:

"< div id="test" class="test"> \n< h3>NAME SPECIALIST< /h3>\n< p>random text< /p>< /div>\n< /div>"

example of package.fields.remarks:

"Arrangement: 3 nachten incl. ontbijt en 2 greenfees p.p. met keuze uit North en South< br>\n- gratis dagelijkse toegang tot de spa (1 uur Hamman, sauna, zwembad, hydromassage)"

example of package.fields.name:

"Shortbreak 3 nachten< br>2 pers./Superior Double/LO, incl. golf"

Getting the warnings in firefox and chrome


回答1:


Demo : https://stackblitz.com/edit/angular-vjt27k?file=app%2Fsanitize-html.pipe.ts

pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'sanitizeHtml'})

export class sanitizeHtmlPipe implements PipeTransform  {
  transform(value) {
    return value.split('< ').join('<');
  }
}



回答2:


As below example if you trying print {} in html angular treats it as expression and will give errors so you can got below options, We have 2 options for HTML sanitization, 1) Using Pipe

 import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'sanitizeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

  constructor(private _sanitizer: DomSanitizer) { }

  transform(value: string): SafeHtml {
    return this._sanitizer.bypassSecurityTrustHtml(value);
  }

}

In Component you can use it as, {{variable | santizeHtml }}

2) Using Component, as an property binding like below, Declare html in .ts file

allowedChars = '@ # $ % ^ & * ( ) _ - ., ? < > { } [ ] ! +';

and use it in template as,

<span [innerHTML]="allowedChars"></span>


来源:https://stackoverflow.com/questions/47528311/angular-5-sanitizing-html-with-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!