Search code examples
angularattributesspecial-characterssanitizerangular-dom-sanitizer

How to show special characters in title attribute on HTML using Angular?


Using Angular in html I need to add title attribute on <a> tag, the value of the title will have text and special characters. The attribute should render tooltip on the anchor, but it is not rendering the special characters, instead I am getting them as a text.

HTML

<a [title]="getSanitizedContent(value)"></a>
<a [title]="value"></a>
<a title="&copy;"></a>

TS

value= '&copy;';

    constructor(private sanitizer: DomSanitizer) {}

    getSanitizedContent(value: string): void {
       return this.sanitizer.bypassSecurityTrustHtml(value);
    }
  • If I use sanitizer I am getting following message in the tooltip safevalue must use [property]=binding:'&copy;'
  • If I use direct value in the tooltip I am getting the text for the special characters instead of icon rendered
  • If I harcode them I can see the special characters rendered well in the tooltip (that means the encoding is correct but the binding is creating issues)

Does anyone know how to show the special characters in the tooltip using title attribute?


Solution

  • The bypassSecurityTrustHtml method from DomSanitizer is intended for use with [innerHTML] binding, not attribute binding. It tells Angular to trust the HTML content and not sanitize it, i believe that's why you’re seeing the

    SafeValue must use [property]=binding message.

    So, to work around it , you can use JS HTMLElement instead, for example

    getSanitizedContent(value: string){
        const txt = document.createElement('textarea');
        txt.innerHTML = value;
        return txt.value;
    }