Reputation: 1760
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
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
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
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
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
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
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
Reputation: 22723
You can use the innerHTML like this:
<span [innerHTML]= "foo"></span>
It will decode properly
Upvotes: 5