1

I have a scenario where I need to display html and xml from the same string sent from the server.

The reply from the server looks like this:

This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.

I tried:

text;
msg = 'This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.'

constructor(private domSanitizer: DomSanitizer) {
}

ngOnInit() {
    this.text = this.getInnerHTMLValue();
}

getInnerHTMLValue() {
    return this.domSanitizer.bypassSecurityTrustHtml(this.msg);
}

html:

<pre [innerText]="text"></pre>

I get this error:

SafeValue must use [property]=binding:...

And when I use [innerHTML] instead of [innerText] the xml has been cleaned out.

How can I display sample xml code along with parsing html tags such as <b> tags? At the very least how can I get rid of that error?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Thibs
  • 8,058
  • 13
  • 54
  • 85

1 Answers1

2

I'm afraid this won't be possible. Have a look at the WC3 specs:

User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them.

Meaning, that although the elements are unknown to your browser, they will be part of the dom and thus not shown in text.

Your only solutions will be either encoding all tags except <b>, <i>,... yourself: <note> -> &#x3C;note&#x3E; or using something like markdown for formatting.

As the easiest workaround, just use msg without sanitizing as it is:

<pre>{{msg}}</pre>

Since it won't be interpreted, sanitizing is not necessary. (Tags like <b> won't be interpreted either, of course.)

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
  • Have a look at this stackblitz for an example: https://stackblitz.com/edit/angular-sanitizing?file=app/button-types-example.ts – Kim Kern Apr 26 '18 at 23:16