When to sanitize while using Angular Renderer2

74 views Asked by At

When I create a text node inside Angular with a sanitized string I unexpectedly got html entities in the output.
I commonly sanitize all my input before using it inside the Renderer2.

const text = '€£';
const safeText = this.domSanitizer.sanitize(SecurityContext.HTML, text) as string;
const child = this.renderer.createText(safeText);
const spanElement = this.renderer.createElement('span');
this.renderer.appendChild(spanElement, child);
this.renderer.appendChild(this.viewContainer.element.nativeElement, spanElement);          

Output generated: €£

See a Stackblitz with a simple demo here.

Native DOM methods like createTextNode or innerText are safe to use, but since the documentation at the createText method doesn't mention in any way what underlying code or mechanism is used to add the text to the DOM it is pretty unclear to me what is safe and what not...

So the question:
Does createText not need sanitizing? (became almost retorical here)
How do I know when to sanitize my content before using it in the Renderer2? Is this documented somewhere? Can I rely on something that is safe today will be also safe in the next release of Angular?


Note: I understand that I can for example change my code to:

const invalidElementText = spanElement.innerHTML(safeText);

But I am not after alternative code that works for this particular case.

1

There are 1 answers

0
Naren Murali On

As you are aware we have innerText and innerHTML, so the first one will accept only text values, wheras the second one will accept html or text.

So You can think of createText to be equivalent to innerText, since the text will never be rendered there is no reason to santize the content of createText. Alternatively when you are inserting html (appendChild), you can sanitize the html before sending to the renderer