Display HTML special characters in Angular 2 bindi

2020-02-24 13:05发布

问题:

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?

回答1:

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



回答2:

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


回答3:

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>



回答4:

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.



回答5:

You can use the innerHTML like this:

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

It will decode properly



回答6:

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



标签: angular