【问题标题】:html tag attributes not working when rendering html through string in angular 6通过角度6中的字符串呈现html时,html标签属性不起作用
【发布时间】:2020-07-19 02:26:45
【问题描述】:

我将 HTML 存储在一个字符串中并在 HTML 文件中使用它,我使用了 HTML sanitize pipe。

下面是我的字符串

  privacyNotice = "<div style=\"color: #ff0000;font-style: italic;\">Before continuing to the  Application, you are required to read and acknowledge this Privacy Notice</div>......<div><input type=\"checkbox\" (change)=\"changeAcknowledgeBtnState()\"/><span class=\"pl-5\">I acknowledge terms of the privacy notice</span> </div> <div>   <button class=\"ackBtn\" [disabled]=\"disableButton\" (click)=\"changePrivacyNoticeStatus()\">Acknowledge </button> </div>";

下面是html文件代码

<div class="container" [innerHTML]='privacyNotice | safeHtml'>

我通过引用this 示例使用了safeHtml 管道

按钮的 disabled 属性不起作用,并且 changePrivacyNoticeStatus() 也没有被调用

【问题讨论】:

  • 您保存字符串而不是显示组件并存储在 json 中的任何具体原因?

标签: html angular typescript angular6 dynamic-html


【解决方案1】:

safeHtml 管道只解析 HTML,无法解析 [disabled]="angularCode()"(click)="changePrivacyNoticeStatus()" 等 Angular 代码。 []() 语法是 Angular 数据绑定语法的一部分,在构建 Angular 项目时会编译到 Javascript 中。您的字符串是在运行时提供的,并且应该是纯的并准备好转为 HTML:它不能在运行时从 Angular 代码解析为 Javascript。

您使用字符串形式的动态内容这一事实被认为是 Angular 中的代码异味,看看您是否无法通过为其编写组件并向组件提供 Inputs 来解决此问题,而不是生成 HTML 代码字符串。

另一种选择可能是内容投影:

<app-privacy-notice>
  <button class="ackBtn" [disabled]="disableButton" (click)="changePrivacyNoticeStatus()">
    Acknowledge
  </button>
  <input type="checkbox" (change)="changeAcknowledgeBtnState()"/>
</app-privacy-notice>

privacy-notice.component.html

<div style="color: #ff0000;font-style: italic;">
  Before continuing to the  Application, you are required to read and 
  acknowledge this Privacy Notice
</div>
<div>
  <ng-content select="input"></ng-content>
  <span class="pl-5">I acknowledge terms of the privacy notice</span>
</div>
<div>
  <ng-content select="button"></ng-content>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 2013-07-23
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多