如何在打字稿中呈现使用 innerHTML 添加的 materail 元素?



使用 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>

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

Angular 清理 DOM 操作,以便不安全(可能被黑客入侵(的东西不起作用。标签很明显,但也不会像其他人那样工作。你还没有说你想要实现什么,所以除了显而易见的 - 从 DOM 插入 DOM(就像你的第一个示例(之外,不可能提出一个好的建议。如果需要条件插入,请使用 ngIf 或 ngSwitch。

最新更新