Angular 2无法正确解析html代码

发布于 2025-01-21 00:05:53 字数 680 浏览 5 评论 0 原文

尝试使用InnerHTML属性来尝试HTML代码以查看所得的HTML,但是如下示例所示,事实并非如此。 HTML代码被视为HTML标签,而不是创建元素,而是将它们作为简单的文本呈现。

https://codepen.io/dralius/dralus/pen/pen/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
  }
}

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='<p> Random Text </p>'
  constructor() {
    // TODO: Define your Angular component implementation
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

做个少女永远怀春 2025-01-28 00:05:53

一个想法可以是使用 domparser (示例)将 notWorking 字符串解析为有效的 html,然后将其注入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='<p> Random Text </p>'
  constructor() { 
    this.notWorking =  new DOMParser().parseFromString(this.notWorking, 'text/html').body.innerText;
  }
}

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='<p> Random Text </p>'
  constructor() { 
    this.notWorking =  new DOMParser().parseFromString(this.notWorking, 'text/html').body.innerText;
  }
}
情域 2025-01-28 00:05:53

这仅仅是因为一个小问题而起作用:只是不会。您不使用HTML标签,只使用它们的“符号”。您在这里到底是什么问题?使用&amp; lt; 主要用于打印页面上的文字符号,而不是作为HTML标签。

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 < is mostly used for printing out the literal symbol on the page, not as HTML tag.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文