本文介绍了通过DomSanitizer在Angular中的类应用样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div [innerHtml]="someHtml | safeHtml"></div>

someHtml = '<span class="fas fa-calendar" style="font-size:15px"></span>'

我通过 innerHtml 属性注入了html元素,并且可以通过绑定 DomSanitizer 管道来应用一些内联样式.但是我想知道是否还有其他方法可以通过 class 应用样式,而不是使用 DomSanitizer 的内联样式.经过一些研究,我可以使其与 :: ng-deep 一起使用,但是根据文档,它似乎已被弃用.任何见识将不胜感激!

I inject a html element through innerHtml property and I could apply some inline-style by binding DomSanitizer pipe. But I wonder if there's any other ways to apply styles through class other than inline-style with DomSanitizer. After some research, I could make it work with ::ng-deep but it seems deprecated according to the docs. Any insight would be appreciated!

推荐答案

您可以在全局样式表中而不是在组件的样式表中为该动态html设置样式.您只需要确保仅针对该动态零件即可,这样您的样式就不会泄漏到其他元素上

You could just set styles for that dynamic html in a global style sheet, instead of in a component's stylesheet. You just have to make sure that you target that dynamic part only, so that your styles don't leak to other elements

global.css

my-component div.dynamicContentWrapper span .fa-calendar
{
    font-size: 15px;
}

component.html

<div "class=dynamicContentWrapper" [innerHtml]="someHtml | safeHtml"></div>

使用ng-deep

Using ng-deep

:: ng-deep 实际上在文档,但是在找到任何替换文档之前它不会消失

::ng-deep is indeed tagged as deprecated in the documentation, but it won't go away before there is any replacement found

用什么代替:: ng-deep

component.css

:host ::ng-deep .fa-calendar {font-size: 15px; }

这篇关于通过DomSanitizer在Angular中的类应用样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:05