简体   繁体   中英

Angular 9: [innerHTML] not working without sanitizing the value even for plain string

I have 2 angular 9 apps in monospace.

The following code prints no text on the browser document in one of the app,

Component:

myText = "some text"

Template:

<p [innerHtml]="myText"><p>

If i write anything inside the paragraph even that is not getting printed:

<p [innerHtml]="myText">Test<p>         // Test is also not getting printed

However,If i sanitize the myText value it works fine.

Component:

// sanitizer is injected DomSanitizer service
myText  = this.sanitizer.bypassSecurityTrustHtml("some text");

Template:

<p [innerHtml]="myText"><p>

But in my other app it works fine.

Has anyone come across similar issue? Is there any app configuration or something which has made sanitization mandatory for innerHTML?

innterHTML will clear out any HTML found within that element (quite literally, the inner html ). If you want to add additional HTML to the template, you'll have to do it in a separate element:

<p [innerHtml]="myText"><p>
<p>some more text</p>

One another thing that you might explore doing is creating your appended value within your TypeScript and appending that to your variable that's getting referenced in the [innerHTML] binding. That would give you a way to stick with one element as opposed to having to append another.

Basically, this is a very similar issue with using something like document.write . document.write clears out the HTML and inserts whatever you passed in. Same thing happens with innerHTML

Basic example of what's happening. Note that "Place holder text" gets completely cleared when innerHTML is set.

 const exampleDiv = document.getElementById('example'); exampleDiv.innerHTML = 'This is some text';
 <div id="example">Place holder text</div>

So, here are your options:

 const exampleDiv = document.getElementById('example1'); const someTextIWantAppended = 'Some appended text'; exampleDiv.innerHTML = `Some Inner HTML I want. ${someTextIWantAppended}`; // OR const exampleDiv2 = document.getElementById('example2'); exampleDiv2.innerHTML = `Some Inner HTML I want.`;
 <strong>Example 1</strong> <div id="example1"></div> <hr /> <strong>Example 2</strong> <div id="example2"></div> <div>Some appended text</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM