Home > Blockchain >  angular 2 does not parse correctly html code
angular 2 does not parse correctly html code

Time:04-14

Trying to HTML code to view the resulting HTML using the innerHTML property, but as you can see in the example below, it doesn't. The HTML code is viewed as the HTML tags and only, instead of creating the elements it renders them as simple text.

https://codepen.io/Dralius/pen/OJzoZxm

@Component({
  selector: 'my-app',
  template: `
  <span [innerHTML]='working'> </span>
   <span [innerHTML]='notWorking'> </span>
  `
})
class AppComponent {  
  working="<h1>hello world angular 6</h1>";
  notWorking='&lt;p&gt; Random Text &lt;/p&gt;'
  constructor() {
    // TODO: Define your Angular component implementation
  }
}

CodePudding user response:

an idea can be to parse the notWorking string into valid html with domparser (for sample) before inject it in innerHTML

https://codepen.io/jeremy-denis/pen/rNpZKzO?editors=1111

const { Component, VERSION } = ng.core;

@Component({
  selector: 'my-app',
  template: `
  <span [innerHTML]='working'> </span>
   <span [innerHTML]='notWorking'> </span>
  `
})
class AppComponent {  
  working="<h1>hello world angular 6</h1>";
  notWorking='&lt;p&gt; Random Text &lt;/p&gt;'
  constructor() { 
    this.notWorking =  new DOMParser().parseFromString(this.notWorking, 'text/html').body.innerText;
  }
}

CodePudding user response:

This won't work just because of one little problem : It just won't. You are not using HTML tags, only the "symbols" of them. What is your problem exactly here? using &lt; is mostly used for printing out the literal symbol on the page, not as HTML tag.

  • Related