I've been trying to render a simple string using [innerHtml] but I keep failing. Basically my issue is when I use <>. For example if my string is:
someText = "abc <1231> color";
I can render
abc <1231> color
but if my string is: "abc <ment1 color" I can only render
abc color
How can I render my string using [innerHtml]?
LIVE DEMO
I've been trying to render a simple string using [innerHtml] but I keep failing. Basically my issue is when I use <>. For example if my string is:
someText = "abc <1231> color";
I can render
abc <1231> color
but if my string is: "abc <ment1 color" I can only render
abc color
How can I render my string using [innerHtml]?
LIVE DEMO
Share Improve this question edited Jul 16, 2021 at 20:29 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Sep 30, 2020 at 20:05 DevmixDevmix 1,8788 gold badges44 silver badges85 bronze badges3 Answers
Reset to default 2If you only want to insert generic text, not actual HTML, you should use the following syntax:
<div>{{someText}}</div>
If it is important for you to use [innerHTML] for any reason, you could use someText = 'abc <1231> color'.replace(/</g, '<')
to strip all your HTML tags and thus resolve your issue.
You can then NOT use any HTML in your element.
To allow specific HTML elements, you could use something like this:
const someText = '<b>Bold Text <123></b>'.replace(/<((b|i|u|strong|a)\s|>)/g, '<$1';
Anyway, it is highly unsafe to insert user generated HTML content into your ponents. You can see this documentation to see, why.
I'd like to add a bit of caution here, because there are a few concerns with the two earlier answer submissions.
First off, I would avoid using innerText
or innerHTML
pletely if you're just trying to display generic text data. Angular has built in data-binding for that very reason and I'd remend using that. As was mentioned in the first part of @nrausch example.
Secondly, If for some reason your ultimate goal is to display HTML via the innerHTML
property to the user, the correct approach is to sanitize the HTML using Angular's built in DOMSanitizer
Here is an example of how to use the DomSanitizer:
First create a sanitization pipe:
import { DomSanitizer } from '@angular/platform-browser'
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Second use the pipe in your ponents HTML:
<div><strong>Binding Example:</strong> {{ name }}</div>
<div [innerHtml]="myHTML | safeHtml"></div>
Here is a StackBlitz Example that shows you both methods.
There is 2 solutions
Using
innerText
instead ofinnerHTML
.Instead of using
<>
onsomeText, you can use
<>to show
<&
>` letters.
someText = "abc <1234> color";
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744684243a4587817.html
评论列表(0条)