Search code examples
javascriptangulartypescriptangular-directive

All special character codes are not converting to respective symbol with Domsanitizer


I have Apostrophe (') code in the string Ex: "Test'Name", Using Domsanitizer I am sanitizing it to convert ' to Apostrophe symbol. But if I have double quotes code ("), it is not being converted to respective symbol. Not only for this, (&) is also not converting from code(&) to symbol. Below is the code I've written so far.

Am I doing correct thing regarding conversion, from code to symbol?

let txt = 'Test"Name';
let txt2 = 'Test'Name';
txt = this.sanitizer.sanitize( SecurityContext.HTML, txt );
txt2 = this.sanitizer.sanitize( SecurityContext.HTML, txt2 );

const ul = this.renderer.createElement('ul');
const li = this.renderer.createElement('li');
const li2 = this.renderer.createElement('li');
const text = this.renderer.createText(txt);
const text2 = this.renderer.createText(txt2);

this.renderer.appendChild(li, text);
this.renderer.appendChild(li2, text2);
this.renderer.appendChild(ul, li);
this.renderer.appendChild(ul, li2);
this.renderer.appendChild(this.el.nativeElement, ul);

Please find the Stackblitz here

Issue 1: Some codes are not being converted to respective symbols

Issue 2: If I have some french characters like é, then it is being converted to code, instead of showing the same (Updated the stackblitz too)


Solution

  • In your case sanitizer converts value to use safely in browser DOM.

    So you need to assign converted value to innerHTML (not to text nodes).

    const ul = this.renderer.createElement('ul');
    const li = this.renderer.createElement('li');
    const li2 = this.renderer.createElement('li');
    li.innerHTML = txt;   // <- inner html
    li2.innerHTML = txt2; // <- inner html
    
    this.renderer.appendChild(ul, li);
    this.renderer.appendChild(ul, li2);
    this.renderer.appendChild(this.el.nativeElement, ul);