DomSanitizer doesn't parse text to HTML

Viewed 200

I am working on an Angular project and I am taking data from a database where it has data with HTML tags. To put it in the HTML I can do that through this code:

[innerHTML]="element.texto"

What Im looking for is to use it on the ts to put the text on a pdf. Im using DomSanitizer but the output is wrong and does not transform it on the HTML. This is the exaple code im using:

import { DomSanitizer } from "@angular/platform-browser";
///
  constructor(
    private sanitizer:DomSanitizer
  ) { }

dataTransformer() {
    let textoHTML = "<p>Hello <b>World</b></p>"
    alert(this.sanitizer.bypassSecurityTrustHtml(textoHTML)) //It shows: SafeValue must use [property]=binding: <p>Hello <b>World</b></p> (see http://g.co/ng/security#xss)
  }

In the other hand, I have used the following code for parseing the code but with a wrong solution.

this.sanitizer.bypassSecurityTrustHtml(textoHTML)['changingThisBreaksApplicationSecurity'] //It shows: <p>Hello <b>World</b></p>

What im looking for is: Hello World

Thanks!

2 Answers

you can use pipe [innerHTML]="element.texto | safeHtml "

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

@Pipe({
  name: 'safeHtml',
  pure: false
})

export class SafeHtmlPipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {
  }

  transform(value: any): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }


}

@erfan-farhadi has given a reusable code.

Use the following as quick fix

Change your ts file to something like this

import { DomSanitizer } from "@angular/platform-browser";

sanitizedValue: undefined; // member var to hold sanitized HTML

constructor(
    private sanitizer:DomSanitizer
) { }

dataTransformer() {
    let textoHTML = "<p>Hello <b>World</b></p>"
    this.sanitizedValue = this.sanitizer.bypassSecurityTrustHtml(textoHTML));
}

/// ...

In html template use like following

[innerHTML]="sanitizedValue"

Related