David
David

Reputation: 1760

Display HTML special characters in Angular 2 bindings?

I have a normal binding like this {{foo}} and it displays foo's value as text in the HTML. The text that comes from the server is "R&D". I need this to display as "R&D". Any help?

Upvotes: 39

Views: 46381

Answers (8)

chezLugi
chezLugi

Reputation: 1

Instead of using [innerHTML] you can also replace accented characters with HexCode (from: Accented Characters and Ligatures in HTML and JavaScript)

For example "R&D" will be saved as "R\x26D"

This way you can use normal binding.

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

Base on accepted answer, I made an sample used

I shared for whom concern.

TS file
    export class AppComponent  {
      cubicSymbol = 'm²';
    }
HTML file
    <h2>Symbol: <span [innerHTML]="cubicSymbol"></span></h2>

https://stackblitz.com/edit/angular-display-symbols

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657158

{{}} is for string binding.

Use attribute binding to innerHTML instead to get these characters displayed correctly.

<div [innerHTML]="foo">

See https://stackoverflow.com/a/41089093/217408 for more details.

Upvotes: 46

Ibrahim Isa
Ibrahim Isa

Reputation: 609

You can also try the binding like this {{"\u0026"}}

Upvotes: 5

dukeluke
dukeluke

Reputation: 656

If you don't want to use [innerHTML], you can use unicode string characters (if you're using unicode strings in your project).

For the '&' symbol, that would be U+0026:

<div>{{"R\u0026D"}}</div>

Upvotes: 15

John Montgomery
John Montgomery

Reputation: 7096

For a little more fun and flexibility, you can create a pipe that parses HTML entities:

@Pipe({name: "decodeHtmlString"})
export class DecodeHtmlString implements PipeTransform {
    transform(value: string) {
        const tempElement = document.createElement("div")
        tempElement.innerHTML = value
        return tempElement.innerText
    }
}

{{foo | decodeHtmlString}}

Upvotes: 29

FAISAL
FAISAL

Reputation: 34673

While innerHTML will work, it will break the line and div will be displayed in the new line (if div is what you prefer to use). Use outerHTML instead. It will add the value of foo at the same place where you use it.

<div [outerHTML]="foo"> </div>

With innerHTML, span is a better option.

Upvotes: 5

Ali Adravi
Ali Adravi

Reputation: 22723

You can use the innerHTML like this:

 <span [innerHTML]= "foo"></span>

It will decode properly

Upvotes: 5

Related Questions