Display HTML special characters in Angular 2 bindings?

后端 未结 7 1315
春和景丽
春和景丽 2020-12-14 15:46

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\"

相关标签:
7条回答
  • 2020-12-14 16:19

    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>

    0 讨论(0)
  • 2020-12-14 16:23

    {{}} 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.

    0 讨论(0)
  • 2020-12-14 16:28

    Base on accepted answer, I made an sample used

    I shared for whom concern.

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

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

    0 讨论(0)
  • 2020-12-14 16:33

    You can use the innerHTML like this:

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

    It will decode properly

    0 讨论(0)
  • 2020-12-14 16:35

    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.

    0 讨论(0)
  • 2020-12-14 16:45

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

    0 讨论(0)
提交回复
热议问题