Hello, I have a string that contains some html code, for example:
text = "<ion-text color='danger'>test</ion-text>";
How can I interpolate it that I don’t get the code as an output but a res “test”?
{{test}}
does not work
Hello, I have a string that contains some html code, for example:
text = "<ion-text color='danger'>test</ion-text>";
How can I interpolate it that I don’t get the code as an output but a res “test”?
{{test}}
does not work
You should read about innerHTML
Some more: https://stackoverflow.com/questions/31548311/angular-html-binding
Okay thank you, but there still is a problem:
if I use <div [innerHTML]="text"></div>
I get the text from the string but not the styling.
If I use
let div = document.getElementById('text');
div.innerHTML = this.text;
it works, why does the other way not work?
Not that you need to care about my opinion, but I hate innerHTML
with a passion, and would like to try to convince you to forget it exists.
One of the great things IMHO about Angular is the way that it cleanly separates parts of an app that are generally developed by different teams, or at the least somebody wearing different “brain-hats” in terms of how they think. Having to wade through TypeScript code in order to change UI layout is frustrating, and similarly so for HTML that is mashed into controller code.
There are also concerns about security, especially when externally-sourced data gets involved. Once you lock those down (many of which Angular’s sanitation does for you, causing further problems once you try to push the envelope of what you can do with innerHTML
), you end up with HTML as a nerfed DSL, and it’s terribly suited for that. It’s tremendously difficult to parse correctly, yet very easy to process unreliably, encouraging all sorts of needless time bombs in your code that won’t bite anybody until somebody, either accidentally or maliciously, drops Little Bobby Tables in there.
So I would urge you not to use HTML outside of templates, where it is written (and can be analyzed) statically. Don’t use it as an intermediate transfer language, don’t process it in your controller code, and don’t inject it with innerHTML
.
Okay I understand your point. I will look for a solution without innterhtml