【问题标题】:How to render the materail element added using innerHTML in typescript?如何在打字稿中渲染使用 innerHTML 添加的材料元素?
【发布时间】:2018-06-14 12:52:09
【问题描述】:

使用innerHTML 属性添加材料设计元素会呈现结果。但是如果我们开发一个具有相同材料设计内容的html页面而不使用innerHTML属性会产生不同的结果。

这里是例子

html文件材料设计内容直接插入

 <div id="requestForm">
   <button mat-raised-button color="primary" id="proceed_btn" style="margin-right: 15px;" (click)="reset()" *ngIf="request_form_selectedIndex > 2">Submit<i class="material-icons right material_icons_btn">send</i>
   </button>
 </div>

在浏览器的 dom 中,上面的页面是这样渲染的。 预期结果

<div id="requestForm">
<button _ngcontent-c3="" color="primary" id="proceed_btn" mat-raised-button="" style="margin-right: 15px;" class="mat-raised-button mat-primary ng-star-inserted" ng-reflect-color="primary">
  <span class="mat-button-wrapper">Submit
    <i _ngcontent-c3="" class="material-icons right material_icons_btn">send</i>
  </span>
  <div class="mat-button-ripple mat-ripple" matripple="" ng-reflect-centered="false" ng-reflect-disabled="false" ng-reflect-trigger="[object HTMLButtonElement]"></div>
  <div class="mat-button-focus-overlay"></div>
</button>

但是当我尝试使用 innerHTML 属性插入材质元素时,它不会呈现相同的结果。

html 文件:

<div id="requestForm">
</div>

ts 文件:

htmlElement1 = "<button mat-raised-button color=\"primary\" id=\"proceed_btn\" style=\"margin: 95px 15px;\" (click) =\"reset()\" *ngIf=\"request_form_selectedIndex > 2\">Submit <i class=\"material-icons right material_icons_btn\">send</i> </button>"

document.getElementById("requestForm").innerHTML = htmlElement1;

在浏览器的 dom 中,上面的页面呈现以下结果。

但我希望在添加材料时获得上述预期结果 元素通过 innerHTML 属性。

我的结果

<div _ngcontent-c3="" id="requestForm">
  <button mat-raised-button="" color="primary" id="proceed_btn" style="margin: 95px 15px;" (click)="reset()" *ngif="request_form_selectedIndex > 2">Submit 
    <i class="material-icons right material_icons_btn">send</i> 
  </button>
</div>

我应该怎么做才能得到预期的结果?

【问题讨论】:

    标签: html typescript angular5 angular-material2


    【解决方案1】:

    Angular 对 DOM 操作进行了清理,因此不安全(可能被黑客入侵)的东西不会起作用。标签很明显,但也不会像其他标签那样好用。您还没有说出您尝试要实现的目标,因此除了显而易见的 - 从 DOM 插入 DOM(如您的第一个示例)之外,不可能提出好的建议。如果需要条件插入,请使用 ngIf 或 ngSwitch。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 2020-12-20
      • 2021-09-04
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多