通过DomSanitizer在Angular中的类应用样式 [英] Apply style through DomSanitizer with class in Angular

查看:41
本文介绍了通过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

不推荐使用穿刺阴影的后代组合器,并且从主要的浏览器和工具中删除了对它的支持.因此,我们计划放弃对Angular的支持(针对/deep/,>>>和:: ng-deep的全部3种).在此之前,应首选:: ng-deep以获得与工具的广泛兼容性.

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

用什么代替:: ng-deep

component.css

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆