0

I have a JSON object that looks like the following:

id:
text: <h1>This is my text</h1> <p> I want to include HTML 
            and reflect those tags on the page. </p>

I'm using Angular2's HTTP_PROVIDER to read the data from the JSON.

In my HTML template, I am displaying the JSON.dataString on the webpage. How do I reflect the HTML tags on the webpage, currently the tags are displayed as plain text.

<p>{{jsonObject.text}}</p>

Is there a way to read in those HTML tags that are included in the JSON objects, and have them reflected on the webpage?

1

3 Answers 3

1

Something like:

<div [innerHTML]="jsonObject.text"></div>

Should display the text object as raw HTML. Be careful about XSS injection when you do something like this.

More detail at this question.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! This worked without the square brackets.. <div innerHTML="{{jsonObject.text}}"></div>
I believe it originally supposed to be <div [innerHTML]="jsonObject.text"></div>". And no, there's no need to worry about XSS, Angular handles this.
@estus By using innerHTML, you are bypassing Angular's encoding of HTML, which means you are bypassing it's XSS protection.
That's not true. The result of innerHTML binding is unescaped, sanitized markup. Harmful things (including anything script-related) can't be added this way to the document. And if you find that they can, feel free to open an issue. See more on the subject.
1

You may try to do it like this:

function textHtml(input) {
    var el = document.createElement("textarea");
    el.innerHTML = input;
    return el.value;
}

And then use this function to get text with tags

Comments

0

I don't use Angular but do something like that.

<p id="myId"></p>
<script>
document.getElementById("myId").appendChild(jsonObject.text);
</script>

I did not test it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.