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);
    }

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;
    }